How do I change the selection in a For loop?

Djbdrake

New Member
Joined
Oct 2, 2019
Messages
6
I'm trying to put a string together, compiling the words in A1:C8, by column. The output for the first column output is A10, the output for the second column is B10 etc. and I want the selection to change each time too so that it only includes column A in the A10 output, column B in the B10 output etc. but the selection just keeps getting added instead so the first output is just column A and then the second output is column is column A and B and the third output is column A, B and C. The code I'm using at the moment is:

Sub test()
For x = 1 To 3
Range(Cells(1, x), Cells(8, x)).Select
Dim rng As Range
Dim i As String
For Each rng In Selection
i = i & rng
Next rng
Cells(10, x).Value = Trim(i)
Next x
End Sub
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
Seems long winded but the quick answer is you need to clear i before the next x

VBA Code:
i = ""
Next X
 
Upvote 0
No need to select. Try this
VBA Code:
Sub test()
    Dim rng As Range
    Dim i As String
    Dim X As Long
    For X = 1 To 3
        For Each rng In Range(Cells(1, X), Cells(8, X))
            i = i & rng
        Next rng
        Cells(10, X).Value = Trim(i)
        i = ""
    Next X
End Sub


It is easier to read your code if you click on </> (above post window) and paste your code into the window that opens up
 
Upvote 0
Hi there. You need to clear i for each column. Try this mod:

VBA Code:
Sub test()
For x = 1 To 3
Range(Cells(1, x), Cells(8, x)).Select
Dim rng As Range
Dim i As String
For Each rng In Selection
i = i & rng
Next rng
Cells(10, x).Value = Trim(i)
i=""
Next x
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,788
Messages
6,121,582
Members
449,039
Latest member
Arbind kumar

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top