从Excel VBA中的一系列单元格创建数组

发布于 2025-02-03 19:59:35 字数 295 浏览 2 评论 0原文

以下内容与我发现的在线解决方案几乎相同:


Dim iAmount() As Variant
Dim INum As Integer

iAmount = Range("C23:W23")
'The example uses iAmount = Range("A1:A11")

For iNum = 1 to Ubound(iAmount)
Debug.Print iAmount(iNum,1)
Next iNum

End Sub

但是,当我尝试使用此数组时,我会收到错误9,这意味着我引用了不存在的变量。

The following is pretty much identical to the solutions online that I've found:


Dim iAmount() As Variant
Dim INum As Integer

iAmount = Range("C23:W23")
'The example uses iAmount = Range("A1:A11")

For iNum = 1 to Ubound(iAmount)
Debug.Print iAmount(iNum,1)
Next iNum

End Sub

However when I try to work with this array I get error 9 which I interpret to mean that I referenced a variable that doesn't exist.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云朵有点甜 2025-02-10 19:59:35

您正在阅读行而不是列,这就是为什么您的代码不起作用的原因。您的范围由1行和21列组成。

您可以读取这样的列:

For INum = LBound(iAmount, 2) To UBound(iAmount, 2)
  Debug.Print iAmount(1, INum)
Next INum

读取任何完整范围的正确方法就是这样:

Dim i As Long, j As Long
For i = LBound(iAmount, 1) To UBound(iAmount, 1)  ' rows
    For j = LBound(iAmount, 2) To UBound(iAmount, 2) ' columns
        Debug.Print iAmount(i, j)
    Next j
Next i

You are reading the rows instead of columns which is why your code doesn't work. Your range is composed of 1 row and 21 columns.

You can read the columns like this:

For INum = LBound(iAmount, 2) To UBound(iAmount, 2)
  Debug.Print iAmount(1, INum)
Next INum

The correct way to read any full range is like this:

Dim i As Long, j As Long
For i = LBound(iAmount, 1) To UBound(iAmount, 1)  ' rows
    For j = LBound(iAmount, 2) To UBound(iAmount, 2) ' columns
        Debug.Print iAmount(i, j)
    Next j
Next i
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文