从 Excel 工作表中提取数据到 VBA:空变量/数组,但 UBound 返回数字

Extracting Data from Excel Sheet to VBA: Empty Variant/Array, but UBound Returns Number

我正在尝试将 Excel 工作表中的文本数据提取到一个数组中(在这种情况下定义为一个变体)。

下面的代码没有返回理想的结果:当我尝试访问 SearchItems 变量数组中的元素时,弹出一个错误,说下标超出范围。

但是,当我运行 UBound(SearchItems) 时,系统会返回 LR 的值(而不是 LR-1?)。

在任何情况下,如果数据已经加载到数组中,这是否表明该数据?

1
2
3
4
5
6
7
8
9
10
Sub Testing()

Dim SearchItems As Variant
Dim LR As Integer

LR = Sheets("MySheet").Cells(Rows.Count,"A").End(xlUp).Row 'Get number of cells in column A

SearchItems = Sheets("MySheet").Range("A1:A" & LR).Value

End Sub


你正在处理一个二维数组:

1
2
3
4
5
6
7
8
9
Sub Testing()
    Dim SearchItems As Variant
    Dim LR As Integer, i As Integer
    LR = Sheets("MySheet").Cells(Rows.Count,"A").End(xlUp).Row 'Get number of cells in column A
    SearchItems = Sheets("MySheet").Range("A1:A" & LR).Value
    For i = 1 To LR
        MsgBox SearchItems(i, 1)
    Next i
End Sub


数组searchitems从0开始,所以ubound当然会在你认为的大小上加1。

如果你需要 Ubound 工作(正如帖子的标题所示):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Sub Testing()
Dim SearchItems() As Variant 'we want SeachItems to be a dynamic array
Dim LR As Long, i As Long

with Sheets("MySheet")
    LR = .Cells(.Rows.Count, 1).End(xlUp).Row 'an other way of Getting the number of cells in column A, note the '.' before rows
    redim SearchItems ( 1 to LR, 1 to 1) ' this way ubound should work
    SearchItems = .Range(.cells(1,1) , .cells(LR,1) ).Value 'an other way of doing it (strangely faster considering its bigger code, tested it)
end with

For i = 1 To LR 'or to Ubound (SearchItems)
    'do stuff with  SearchItems(i, 1)
Next i


'to write it back to the worksheet :
Sheets("MySheet").Range("A1:A" & LR).Value = SearchItems

End Sub