【问题标题】:Extracting Data from Excel Sheet to VBA: Empty Variant/Array, but UBound Returns Number从 Excel 工作表中提取数据到 VBA:空变量/数组,但 UBound 返回数字
【发布时间】:2014-03-27 20:07:58
【问题描述】:

我正在尝试将 Excel 工作表中的文本数据提取到数组中(在本例中定义为变体)。

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

但是,当我运行 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

【问题讨论】:

标签: vba excel variant


【解决方案1】:

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

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

【讨论】:

  • 谢谢,我习惯了 MATLAB,没想到它会默认为 2D。
  • 唯一的一维是单个单元格。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 2018-04-05
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多