循环列VBA excelmacros

我在excel VBA中循环遍历列遇到麻烦。 我不确定范围,我应该使用正常范围,我们有字母作为列? 如何循环使用字母。

我已经尝试了不同的代码,但他们不工作。 例如:

Sub copytest() Dim x As Workbook Dim j As Integer, i As Integer Application.ScreenUpdating = False Workbooks.Open ("D:\test\COMP.xlsx") i = 3 For j = 3 To 14 Sheets("Compliance").Range(Cells(18, i), Cells(30, i)).Copy Windows("KP.xlsm").Activate Sheets("MOH").Range(Cells(12, j), Cells(24, j)).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False i = i + 2 Next j x.Close End Sub 

您可以将数字用于列。 假设你想循环前5行和前5列,那么你可以把它写成

 For i = 1 To 5 '<~~~ Rows For j = 1 To 5 '<~~~ Columns With ThisWorkbook.Cells(i, j) '~~> Do something End With Next j Next i 

在Excel 2013中,最后一列是列号为16384的XFD。

 A - 1 B - 2 C - 3 . . and so on... XFD - 16384 

如果你想循环使用列名,那么你可以这样使用它

 Dim ColName As String For i = 1 To 5 '<~~~ Rows For j = 1 To 5 '<~~~ Columns ColName = Split(Cells(, j).Address, "$")(1) With ThisWorkbook.Range(ColName & i) '~~> Do something End With Next j Next i 

循环虽然列的替代方法是For Each cell in my1RowRange循环中的For Each cell in my1RowRange ,其中

  • cell是一个单元格Range对象,它循环遍历my1RowRange Range

  • my1RowRange必须是1行Range

除此之外,你的代码有一些主要的缺陷:

  • 您的范围引用使用简单的 Cells(...)引用,没有任何明确的worksheetworkbook引用之前

    以便他们继续在活动 worksheet workbook引用活动 worksheet

    这是不好的,因为在你的循环中,你似乎只是改变正确的工作簿,而实际上只是一开始就改变它( Windows("KP.xlsm").Activate ),然后它始终是唯一的参考工作簿

  • 避免Activate / ActiveXXX (以及Select / Selection )编码,因为

    • 这很容易出错,就像事实certificate这是正确的,因为它最有可能导致你失去对实际活动工作簿/工作表的控制

    • 这是费时,并获得屏幕闪烁

所以考虑下面的代码重构:

 Option Explicit Sub copytest() Dim i As Long Dim compWb As Workbook Dim compRng As Range, cell As Range Set compWb = Workbooks.Open "D:\test\COMP.xlsx" '<--| set the workbook to open to a specific variable of 'Workbook' type With compWb.Worksheets("Compliance") '<--| refer to "compliance" worksheet of the "right" (you're explicitly referencing it!) workbook Set compRng = .Range(.Cells(18, 3), .Cells(30, 3)) '<--| set the "source" range: all the dots means we're referencing the object after the last "With" statement End With i = 3 With Workbooks("KP.xlsm").Worksheets("MOH") '<--| refer to "MOH" worksheet of "KP" workbook For Each cell In .Range(.Cells(12, 3), .Cells(12, 14)) '<--| loop through cells of a 1-row range of the referenced worksheet: this means looping through columns! cell.Resize(13).Value = compRng.Offset(, i - 3).Value '<--| paste values while offsetting the "souce" range columns (first iteration with offset=0) i = i + 2 Next cell End With compWb.Close '<--| close the opened workbook End Sub