vba 将范围值传递给数组时,为什么数组索引从 1 开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24007320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:20:18  来源:igfitidea点击:

Why array Index starts at 1 when passing range values to array

excel-vbavbaexcel

提问by user3701617

In this VBA program all I am trying to do is to pass an array from spreadsheet and add 1 to each of the array's cells. My problem is with the index of the array. when I start looping the array it doesnt work when I start the index from zero ( I get error subscript out of range) but it works perfectly when I start the array from 1. Why is that? (I thought that would be the case only I specify at the top Option Base 1)

在这个 VBA 程序中,我想要做的就是从电子表格中传递一个数组并将 1 添加到数组的每个单元格中。我的问题是数组的索引。当我开始循环数组时,当我从零开始索引时它不起作用(我得到错误下标超出范围)但是当我从 1 开始数组时它工作得很好。为什么会这样?(我认为只有我在顶部Option Base 1指定了这种情况)

Sub Passarray()
    Dim Array As Variant
    Dim i, j As Integer
    'Pass array and manipulate
    Vol = Range("Volatility")
    For i = 0 To 2
       For j = 0 To 2
          Vol(i, j) = 1+ Vol(i,j)
       Next j
    Next i
End Sub

回答by L42

That wasn't the case when you pass Rangeto arrays based on my experience.
I don't know the specific reason behind, but this linkindicates that you cannot change this behavior.

根据我的经验,当您将Range传递给数组时,情况并非如此。
我不知道背后的具体原因,但此链接表明您无法更改此行为。

QUOTE: The array into which the worksheet data is loaded always has an lower bound (LBound) equal to 1, regardless of what Option Base directive you may have in your module. You cannot change this behavior.

引用:加载工作表数据的数组始终具有等于 1 的下限 (LBound),无论您的模块中可能有什么 Option Base 指令。您无法更改此行为。

What you can do is to utilize the use of LBound/UBoundlike this:

您可以做的是像这样使用LBound/UBound

Vol = Range("Volatility")
For i = LBound(Vol, 1) To UBound(Vol, 1)
    For j = Lbound(Vol, 2) To Ubound(Vol, 2)
        '~~> do stuff here
        Vol(i, j) = 1 + Vol(i, j)
    Next j
Next i

If however your Rangeis just one column with several rows, you pass it to Array like this:

但是,如果您的Range只是一列多行,则可以像这样将其传递给 Array:

Vol = Application.Transpose(Range("Volatility"))
For i = LBound(Vol) To UBound(Vol)
    '~~> do stuff here
    Vol(i) = 1 + Vol(i)
Next

This way, you will produce one-D array instead of two-D array.
To iterate values you can use above or you can also use For Each:

这样,您将生成一维数组而不是二维数组。
要迭代您可以在上面使用的值,也可以使用For Each

Dim x As Variant '~~> dimension another variant variable
For Each x In Vol
    '~~> do stuff here
    x = 1 + x
Next