【问题标题】:Empty output when populating 2D range with array用数组填充二维范围时的空输出
【发布时间】:2020-03-20 16:36:47
【问题描述】:

我正在尝试使用 2D 数组填充 2D 范围。

目前我有这个:

Sub populate()

Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Sheet1")

Dim Rows(2) As Variant

Rows(0) = [{1, 2, 3}]
Rows(1) = [{4, 5, 6}]
Rows(2) = [{7, 8, 9}]

With ws
    .Range(.Cells(1, 1), .Cells(3, 3)).Value = Rows
End With


End Sub

我没有收到任何错误等,但运行宏后范围仍然为空

最奇怪的是,当我走的时候,我得到了正确的输出:

With ws
    .Range(.Cells(1, 1), .Cells(3, 3)).Value = Application.Transpose(Application.transpose(Rows))
End With 

我浏览了许多文章和 Microsoft 文档,但没有任何东西可以解决我的问题。

【问题讨论】:

  • Rows() 是一维数组,其元素是一维数组。你需要得到一个真正的二维数组
  • 声明Dim Rows(2, 0) As Variant
  • 您已经有了一个工作选项,所以我不太清楚您在寻找什么?您可以简单地创建一个二维数组:Dim Rows() As Variant: Rows() = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]
  • 如果你想使用Evaluate,那么不妨试试:Rows(0,0) = [Row(1:3)]Rows(1,0) = [Row(4:6)]Rows(2,0) = [Row(7:9)]。那是你想要做的吗?检查语言环境变量窗口以查看所有不同选项对您的数组的作用。
  • 使用我的最后一条评论,您可以通过Rows(0, 0)(1, 1) = "Your value" 添加一个值,这将更改您的 2D 数组的第一个元素中第一个 2D 数组的第一个元素的值 =).. .....ehh,是的,正确的哈哈

标签: arrays excel vba range


【解决方案1】:

我不了解您为什么对二维数组中的二维数组感兴趣,但是(也根据@Rory 他的评论,您可以尝试以下操作:

Sub populate()

Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Blad1")

Dim Rows(2, 0) As Variant

Rows(0, 0) = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]
Rows(1, 0) = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]
Rows(2, 0) = [{1, 2, 3; 4, 5, 6; 7, 8, 9}]

'Rows(0,0)(1,1) = "value" 'If you want to change. This example will change the first element of the 2D-array within the first element of your first 2D-array.

With ws
    .Range(.Cells(1, 1), .Cells(3, 3)).Value = Application.Transpose(Application.Transpose(Rows(0, 0))) 'Will transpose your first element in your initial 2D-array (not sure if this is put correctly in English)
End With

End Sub

如果您想对二维数组中的每个元素执行上述操作,您可以实现For x = Lbound(rows) to Ubound(rows)

在聊天中,很明显 OP 还希望实现以下功能:

reasonArr(1, 0) = [{0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0; 0,0,0,0,0,0,0,0,0,0,0,0}]

这引发了错误。这是因为提供给 Evaluate 的行超过了 255 个字符。

【讨论】:

  • 谢谢,但我已经拿到了。让我们继续聊天吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多