【问题标题】:read variable excel data into variant with the same format将变量excel数据读入具有相同格式的变量
【发布时间】:2015-06-17 07:43:19
【问题描述】:

我目前正在为 Excel 编写宏。首先,我想将我的工作表“Filter”中第 20 行的变量设置读取到我的变量“test”中:

' Define Last Column with a value
LastCol = Sheets("Filter").Cells(20, Sheets("Filter").Columns.Count).End(xlToLeft).Column
Col_Letter = Split(Cells(1, LastCol).Address(True, False), "$")(0)

' Read Data into variable
test = Sheets("Filter").Range("B20:" & Col_Letter & "20").Value

到目前为止,这工作正常,我得到了一个具有类似结构的变体:

test
  test(1)
    test(1,1) = value1
    test(1,2) = value2
    test(1,3) = value3
    ...

我的问题来了: 当我只有一个值要读取时,结构会自动更改为:

test = value1

如何将结构更改为这个?

test
  test(1)
    test(1,1) = value1

我的问题是,使用这个变量时,我在代码中遇到了各种问题(ubound、lbound、...)。

【问题讨论】:

  • 您的其他代码应该在尝试循环之前检查test 是否是一个数组。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 感谢您的意见!我猜 R3uK 有最结构化的答案:)

标签: vba excel variables data-structures


【解决方案1】:

如果最后一列为 B 或更少,您可以强制 test 成为一个只有一个单元格的数组:

' Define Last Column with a value
LastCol = Sheets("Filter").Cells(20, Sheets("Filter").Columns.Count).End(xlToLeft).Column
Col_Letter = Split(Cells(1, LastCol).Address(True, False), "$")(0)

If LastCol <= 2 Then
    ReDim test(1 To 1, 1 To 1)
    test(1, 1) = Sheets("Filter").Range("B20").Value
Else
    'Read Data into variable
    test = Sheets("Filter").Range("B20:" & Col_Letter & "20").Value
End If

【讨论】:

  • 非常感谢您的意见!工作得很好:) 如此简单,却解决了我数小时的问题!
  • 很高兴能帮上忙! ;) 通常会花几个小时在一个简单的问题上,因为我们无法了解所有技巧,这就是该网站如此神奇/实用的原因!
【解决方案2】:

你可以检查长度..试试下面的代码:

Dim test As Variant
test = Sheets("Filter").Range("B20:" & Col_Letter & "20").Value
If Len(test) = 1 Then
        ReDim test(1, 1)
        test(1, 1) = Sheets("Filter").Range("B20:" & Col_Letter & "20").Value
End If

【讨论】:

  • 这里,使用ReDim test(1 To 1, 1 To 1) 可能更实用,因为对于您的解决方案,LBound(test,1)=0LBound(test,2)=0 所以会有3 个空单元格(test(0,0)test(1,0) 和@ 987654327@) 在该数组中。
猜你喜欢
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多