使用数组vba为单元格指定值/字符串

时间:2017-11-17 18:35:40

标签: excel vba excel-vba

我正在尝试使用数组为列z赋值,但我没有获得期望结果。我正在测试分配单元格Z1 = A,单元格Z2 = B,单元格Z3 = C 现在我的代码将所有3个单元格分配给C.我已经在下面发布了我的愿望结果。

Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(i)
            Next j
        Next i
End With

End Sub

enter image description here

4 个答案:

答案 0 :(得分:3)

您可以设置选项库1,因此在写入值时使用有效行引用(如果数组lbound为0,则无法使用.Cells(0,26)= v(0),因为没有第0行表。

Option Base:在模块级别用于声明数组下标的默认下限。默认值为0。

使用Base 1意味着可以访问所有数组元素并对sheet和array使用相同的增量变量,即只能使用一个长变量i。

Option Base 1
Sub test()

Dim ws1 As Worksheet
Dim i Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")

v = Array("A", "B", "C")

With ws1

        For i = LBound(v) To UBound(v)
                   .Cells(i, 26) = v(i)               
        Next i

End With

End Sub

答案 1 :(得分:2)

要了解如何在单元格中读取和写入1D或2D VBA阵列,请查看以下代码:

Public Sub TestArrayReadAndWrite()

    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")

    ' Set a 1D array in VBA
    ' Write the array to cells
    Dim v() As Variant
    v = Array("A", "B", "C")
    ws.Range("A1").Resize(3, 1).Value = WorksheetFunction.Transpose(v)
    ws.Range("A5").Resize(1, 3).Value = v

    ' Set a 3×3 array in VBA
    ' Write the array to cells
    Dim a() As Variant
    ReDim a(1 To 3, 1 To 3)
    a(1, 1) = "A11": a(1, 2) = "A12": a(1, 3) = "A13"
    a(2, 1) = "A21": a(2, 2) = "A22": a(2, 3) = "A13"
    a(3, 1) = "A31": a(3, 2) = "A32": a(3, 3) = "A13"

    ws.Range("C1").Resize(3, 3).Value = a

    ' Read Array 100×1 array of cells
    ' Modify the array by doubling the values
    ' Write the array back to the next column over
    Dim b() As Variant, i As Long
    b = ws.Range("G1").Resize(100, 1).Value
    For i = 1 To 100
        b(i, 1) = 2 * b(i, 1)
    Next i
    ws.Range("G1").Offset(0, 1).Resize(100, 1).Value = b
End Sub

结果:

RES

使用一个命令编写整个数组,通过分配给Range().Resize(n,m).Value = x然后循环遍历所有值并一次设置一个来快速简洁。

答案 2 :(得分:0)

试试这个

Sub test()

Dim ws1 As Worksheet
Dim i, j As Long
Dim v As Variant

Set ws1 = Worksheets("Sheet1")
With ws1
    v = Array("A", "B", "C")
        For i = LBound(v) To UBound(v)
            For j = 1 To 3
                Cells(j, 26).Value = v(j - 1)
            Next j
        Next i
End With

End Sub

答案 3 :(得分:0)

这个简单的代码怎么样。

Private Sub cmdFill_Click()
Dim i As Integer
    For i = 1 To 26
        Cells(i, 26).Value = Chr(64 + i)
    Next i
End Sub

如果只需要3,则可以调整26。