Link to home
Start Free TrialLog in
Avatar of AKSkiBum
AKSkiBum

asked on

Excel VBA - For Each in Selection - identify last cell in Selection

Hi,

I have some simple code to loop through each cell in a selection to modify it but I would like to modify the last cell in the selection differently.

Is there a simple method to identify when the For Each loop has reached the last cell in the Selected range?

Here's a simple example. For this example, I'm adding a comma to each cell so I can drop the selected cells into an SQL In statement. I don't want the last cell to have a comma added.

Sub AddComma()
Dim cell As Range
For Each cell In Selection
    cell.Value = cell.Value & ","
    Next cell
End Sub
Avatar of ItryToXL
ItryToXL

Sub AddComma()
For Each cell In Selection
    cell.Value = cell.Value & ","
    LastCell = cell.Address
Next cell
Range(LastCell).Clear
End Sub
ASKER CERTIFIED SOLUTION
Avatar of Kimputer
Kimputer

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AKSkiBum

ASKER

Thanks for the code! Works great.