KD Jayakody

Call Us: 076 72 33 595

Automating Cell Interaction in Excel: VBA Included

Nov 7, 2023

This code empowers you to easily set values in A3 cells with a simple click on either A1 or B1 cells in Excel. By providing a straightforward solution, it streamlines the process of updating A3 cells, making it more efficient and user-friendly. Whether you’re a novice or an experienced Excel user, this code simplifies cell interactions and enhances your Excel experience.

Code Part 01

This code will give you the ability to set the values to the A3 cells when you click on A1 or B1 cells.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address = "$A$1" Then
' Append the value from A1 to A3
Range("A3").Value = Range("A3").Value & Range("A1").Value
ElseIf Target.Address = "$B$1" Then
' Append the value from B1 to A3
Range("A3").Value = Range("A3").Value & Range("B1").Value
End If
End Sub


Code Part 02

This code is designed to append the value of the previously selected cell, offering a versatile solution for automating actions in Excel. Unlike many macros that target a single cell, this code allows you to interact with and modify multiple cells dynamically. It provides flexibility and customization to suit your specific needs.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Display the address (cell name) of the currently selected cell in K1
If Target.Address = "$A$1" Or Target.Address = "$B$1" Then
' Store the value in K1
K1Value = Range("K1").Value
' Display the address (cell name) in K1 if it's not A1 or B1
Range("K1").Value = Target.Address
End If
If K1Value <> "" Then
' Append the value from A1 or B1 to the previously selected cell (stored in K1)
Dim prevSelectedCell As Range
Set prevSelectedCell = Range(K1Value)

If Target.Address = "$A$1" Then
prevSelectedCell.Value = prevSelectedCell.Value & Range("A1").Value
ElseIf Target.Address = "$B$1" Then
prevSelectedCell.Value = prevSelectedCell.Value & Range("B1").Value
End If
End If
End Sub

Hope this tutorial helped you a lot. if you need to follow my course, please contact KDJ Education on 076 72 33 595 (WhatsApp). We got a 4 Days Fully Explain Short Course for you to enhance your knowledge in Excel and Python.


Recent Posts