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

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

下面的代码不会返回所需的结果:当我尝试访问SearchItemsvariables数组中的元素时,popup一个错误,指出下标超出范围。

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

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

 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 

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

 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 

数组search项从0开始,所以ubound当然会给你想象的大小加1。

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

 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