将值赋给二维数组

时间:2014-11-11 07:49:46

标签: arrays vba excel-vba excel

我正在尝试将值分配给VBA中的2D数组,但它无法正常工作。 这是我尝试过的:

Sub UpdateCustomName()
    Dim CellTags() As String
    Dim temp() As String
    Dim ControlName As String
    Dim CellValue As String
    Dim CustomName(1 To 2, 1 To 2) As String

    For Each Cell In ActiveSheet.UsedRange.Cells
        If Not Cell.Value = "" Then
            CellTags() = Split(Cell.Value, "*")
            ' here in CellTags(2) value is like ABC_E34
            CustomName() = Split(CellTags(2), "_")
            MsgBox CustomName(1, 2)
        End If
    Next

End Sub

3 个答案:

答案 0 :(得分:1)

CustomName声明为动态数组:

Dim CustomName() As String

请注意Split返回一维(不是二维)数组。所以MsgBox CustomName(1, 2)将不起作用。相反,请尝试,例如:MsgBox CustomName(0) & " and " & CustomName(1)

答案 1 :(得分:1)

Split返回一个数组,我认为你不能在VBA中将数组的值设置为数组。这对你有帮助吗?

Sub UpdateCustomName()
    Dim CellTags() As String
    Dim temp() As String
    Dim ControlName As String
    Dim CellValue As String
    Dim CustomName() As String
    Dim iCount As Long

    ' Redimension the array here, we cannot use a variable to dimension it in a Dim statement,
    'and it needs to be big enough to hold the data but not so big it wastes memory.
    ReDim CustomName(0 To ActiveSheet.UsedRange.Cells.Count - 1, 0 To 1) As String

    For Each Cell In ActiveSheet.UsedRange.Cells
        If Not Cell.Value = "" Then
            CellTags() = Split(Cell.Value, "*")
            CustomName(iCount, 0) = Split(CellTags(1), "_")(0)
            CustomName(iCount, 1) = Split(CellTags(1), "_")(1)
            MsgBox CustomName(iCount, 0) & " : " & CustomName(iCount, 1)
            iCount = iCount + 1
        End If
    Next
End Sub

答案 2 :(得分:1)

Sub UpdateCustomName()
    Dim myCell As Range
    Dim CellTags() As String
    Dim temp() As String
    Dim ControlName As String
    Dim CellValue As String
    Dim CustomName(1 To 2, 1 To 2) As String

    For Each myCell In ActiveSheet.UsedRange.Cells
        If Not myCell.Value = "" Then
            CellTags() = Split(myCell.Value, "*")
            ' here in CellTags(2) value is like ABC_E34
            CustomName(1, 1) = Split(CellTags(2), "_")(0)
            CustomName(1, 2) = Split(CellTags(2), "_")(1)
            MsgBox CustomName(1, 2)
        End If
    Next
End Sub
  

如果单元格包含值' 1 * 2 * ABC_E34 '然后:

enter image description here

  

有关VBA中2D阵列的信息:

http://www.homeandlearn.org/multidimensional_arrays.html