简体   繁体   English

使用VBA在Excel工作簿的第二张工作表上运行循环

[英]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. 我正在尝试运行Do While循环以将工作簿的Sheet2的新列上的Sheet2的三列连接起来,我认为我引用第二个工作表的方式会使其出错,因为在第一张表上运行此代码会给我带来积极的结果, 任何帮助将非常感激。

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. 否则,Excel将尝试基于活动的工作表(在上面的代码中是Sheet2)进行猜测。 (The ActiveWorkbook.Worksheets("Sheet2").Activate at the top sets it as the ActiveSheet) (ActiveWorkbook.Worksheets(“ Sheet2”)。在顶部激活将其设置为ActiveSheet)

So for example, to reference a cell on Sheet 1: 因此,例如,要引用工作表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. 谢谢Leowyn抢先一步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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