[英]Loop columns using 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中,最后一列是XFD,其列號為16384。
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
是在my1RowRange
Range
上循環的單單元格Range
對象
my1RowRange
必須為1行Range
除此之外,您的代碼還存在一些主要缺陷:
您的范圍引用使用簡單的 Cells(...)
引用,之前沒有任何明確的worksheet
和workbook
引用
這樣他們就可以繼續引用活動 worksheet
workbook
中的活動 workbook
worksheet
這是不好的,因為在循環過程中,您似乎只在不斷更改正確的工作簿,而實際上在開始時只對其進行了一次更改( Windows("KP.xlsm").Activate
),然后它始終是唯一被引用的工作簿工作簿
避免使用Activate
/ ActiveXXX
(以及Select
/ Selection
)編碼,因為
它容易出錯,就像事實證明的那樣,因為它很可能導致您失去對實際活動工作簿/工作表的控制
這很耗時,並且會出現屏幕閃爍
因此,請考慮以下代碼重構:
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.