简体   繁体   中英

Running loop on second sheet in Excel Workbook with VBA

I am trying to run a Do While loop to concatenate three columns on Sheet2 on a new column of Sheet2 of my Workbook, I think how I am referencing my second worksheet is tripping this up as running this code on the first sheet gives me positive results, any help would be much appreciated.

ActiveWorkbook.Worksheets("Sheet2").Activate

Dim noSep As String
noSep = ""

Cells(1, 3) = col1
Cells(1, 30) = col2
Cells(1, 32) = col3
Cells(1, 63) = colconcatenated

x = 2

Do While Worksheets("Sheet2").Cells(x, col1) <> ""
Cells(x, coloncatenated) = Cells(x, col1) & noSep & Cells(x, col2) & noSep & Cells(x, col3)
x = x + 1
Loop
Columns("BK:BK").EntireColumn.AutoFit

It's hard to tell from your question, but in general, if you are working with more than one sheet at a time, you should qualify all of your references to Cells/Ranges on those sheets to specify which sheet you are working with.

Otherwise, Excel will try to guess based on which sheet is active, which in your code above is Sheet2. (The ActiveWorkbook.Worksheets("Sheet2").Activate at the top sets it as the ActiveSheet)

So for example, to reference a cell on Sheet 1:

Worksheets("Sheet1").Cells(1,3) = col1

Alternatively, you can Dim a couple variables to refer to the two sheets, which might make the code easier to read:

Dim shtA as Worksheet
Dim shtB As Worksheet

Set shtA = Sheets("Sheet1")
Set shtB = Sheets("Sheet2")

shtA.Cells(1, 3) = col1

Hope that helps!

I ended up having to basically rebuild it and destroy all the junked code from a previous dev. Once I started over, specifying the sheet to work with when it is not the active worksheet solved my problem. My macro is functioning perfectly.

Thank you Leowyn for the head start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM