简体   繁体   English

使用VBA循环列

[英]Loop columns using VBA

I want to loop through columns. 我想遍历各列。

I'm not sure about the range. 我不确定范围。 Should I use normal range where we have the alphabets as columns? 我应该在字母作为列的地方使用正常范围吗?

I tried different codes. 我尝试了不同的代码。 For example: 例如:

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

You can use numbers for columns. 您可以将数字用于列。 Let's say you want to loop through first 5 rows and first 5 columns then you can write it as 假设您要遍历前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

In Excel 2013, the last column is XFD which is column number 16384. 在Excel 2013中,最后一列是XFD,其列号为16384。

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

If you would like to loop using Column Names then you can use it as such 如果您想循环使用列名,则可以这样使用它

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

an alternative for looping though columns is a For Each cell in my1RowRange loop, where 通过列循环的另一种方法是For Each cell in my1RowRange循环中的For Each cell in my1RowRange ,其中

  • cell is a single-cell Range object that loops over my1RowRange Range cell是在my1RowRange Range上循环的单单元格Range对象

  • my1RowRange must be a 1-Row Range my1RowRange必须为1行Range

besides that, your code has some major flaws: 除此之外,您的代码还存在一些主要缺陷:

  • your range references use simple Cells(...) reference without any explicit worksheet and workbook reference before them 您的范围引用使用简单的 Cells(...)引用,之前没有任何明确的worksheetworkbook引用

    so that they keep referencing the active worksheet in the active workbook 这样他们就可以继续引用活动 worksheet workbook中的活动 workbook worksheet

    and this is no good since during your loop you only seem to keep changing the right workbook while you're actually only changing it once at the beginning ( Windows("KP.xlsm").Activate ) and then it always remains the only referenced workbook 这是不好的,因为在循环过程中,您似乎只在不断更改正确的工作簿,而实际上在开始时只对其进行了一次更改( Windows("KP.xlsm").Activate ),然后它始终是唯一被引用的工作簿工作簿

  • avoid Activate / ActiveXXX (as well as Select / Selection ) coding, since 避免使用Activate / ActiveXXX (以及Select / Selection )编码,因为

    • it's error prone, like it proved to be right here, since it most likely lead you to loose control over actual active workbook/worksheet 它容易出错,就像事实证明的那样,因为它很可能导致您失去对实际活动工作簿/工作表的控制

    • it's time consuming and gets screen flickerings 这很耗时,并且会出现屏幕闪烁

so consider the following refactoring of your code: 因此,请考虑以下代码重构:

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
Sub Columns()

Dim rng As Range
Dim col As Range
Sheets("Sheet1").Select 'make shure its in the correct sheet

Set rng = Range("C3:G6") 'select the range of the whole table


For Each col In rng.Columns 'this performs a tasks column by column
    'Do Something
    col.Select
    Selection.RemoveDuplicates Columns:=1, Header:=xlNo
    'end something

Next col 'move to next column

End Sub

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

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