将单元格分配给For循环中的变体

时间:2017-11-20 21:44:08

标签: vba

我必须在vba中输入数千个单元格引用。到目前为止,一切正常,但我无法弄清楚如何将“MyValue”编码为for循环。有什么建议?

Dim MyValue1 As Variant
Dim MyValue2 As Variant
Dim MyValue3 As Variant
Dim MyValue4 As Variant
Dim MyValue5 As Variant


MyValue1 = Cells(3, 5).Value
MyValue2 = Cells(4, 5).Value
MyValue3 = Cells(5, 5).Value
MyValue4 = Cells(6, 5).Value
MyValue5 = Cells(7, 5).Value

Mooseman,每个值都必须是唯一的才能通过访问来执行插入功能。当代码写得像这样有效时,我正在寻找一个循环函数来完成这个技巧。

Dim MyVariant(1 To 5) As Variant
Dim i As Long
For i = 1 To 5
    MyVariant(i) = Worksheets("Data").Cells(i + 2, 5)
Next i

我尝试了每个人的建议,但它们似乎没有用。这是我收到的错误消息:

"Run-time error '-2147467259(80004005' Automation error Unspecified Error

3 个答案:

答案 0 :(得分:0)

使用数组然后循环:

Dim MyValue(0 to 9) As Variant
Dim i As Long

For i = 0 to 9
    MyValue(i) = ActiveSheet.Cells(i+2,5).Value
Next i

或者因为这些值是连续的:

Dim MyValue() as Variant
MyValue = ActiveSheet.Range(ActiveSheet.Cells(2,5),ActiveSheet.Cells(11,5)).Value

答案 1 :(得分:0)

这完全取决于你想对MyValue做些什么,但它可以很简单:

Dim MyValue as Long
Dim i As Long
For i = 2 To 11
    MyValue = Cells(i, 5)
Next i

但这只会将单元格中的值复制到单个变量中。

您还可以将所有这些值放入这样的数组中:

Dim MyValue(2 To 11) as Long
Dim i As Long
For i = 2 To 11
    MyValue(2) = Cells(i, 5)
Next i

您必须定义更多您想要做的事情。

答案 2 :(得分:0)

简短的回答,不要。改为使用数组:

Dim cellValues As Variant

cellValues = Range("E2:E100").Value

For i = 1 To UBound(cellValues)
    Debug.Print cellValues(i, 1)
Next