我正在尝试使用循环和vba中使用的range函数创建一个数组。但是,我只想要特定列的使用范围,而没有标题(每列的第一行)。我的代码如下-除了第一行之外,我不确定如何找到所有内容。
谢谢。
Col(1) = 9
Col(2) = 11
Col(3) = 13
Col(4) = 15
Col(5) = 17
Col(6) = 19
Col(7) = 21
Col(8) = 23
Col(9) = 25
Col(10) = 27
Col(11) = 29
Dim myArray() As Variant, myArray2() As Variant
Dim DataRange As Range
Dim cell As Range
Dim x As Long
For i = 1 To 11
Set DataRange = Worksheets(12).UsedRange.Columns(Col(i))
For Each cell In DataRange.Cells
ReDim Preserve myArray(x)
myArray(x) = cell.Value
x = x + 1
Next cell
Next i
答案 0 :(得分:0)
您需要做的是,除了将Header Row用作DataRange之外,不要使用Usedrange。
您可以执行以下操作。
For i = 1 To 11
lastRow = Worksheets(12).Cells(Rows.Count, col(i)).End(xlup).Row 'This is to find the last used row for the certain column.
Set DataRange = Worksheets(12).Range(Cells(2,Col(i)),Cells(lastRow,Col(i)))
Next i
现在,您将拥有所需的特定范围。
您可以执行的另一件事是为您的范围添加一个附加的if语句,以检查单元格的行是否为标题。
For i = 1 To 11
Set DataRange = Worksheets(12).UsedRange.Columns(Col(i))
For Each cell In DataRange.Cells
If cell.Row > 1 then
ReDim Preserve myArray(x)
myArray(x) = cell.Value
x = x + 1
End if
Next cell
Next i