编辑数组时出错

时间:2014-06-13 16:41:55

标签: arrays excel vba excel-vba

我正在使用Arrays并尝试将数组的文本值更改为数字,以便在代码进度时更容易进行评估。我似乎遇到了阵列问题,但我不确定为什么。你能看看我的代码并提供反馈吗?

Dim MonthlyValuesUnclean() As Range
Dim CodeCountOne As Long

Range("A1").Select
CodeCountOne = Application.CountA(Range("A:A")) 'Counts Total Number of Codes Before Clean
ReDim MonthlyValuesUnclean(CodeCountOne, 1 To 3)

For columnNumber = 1 To 3
    ReDim MonthlyValuesUnclean(CodeCountOne, columnNumber)
    For counter = 1 To CodeCountOne

        If MonthlyValuesUnclean(counter, columnNumber).Text = "R" Then
            MonthlyValuesUnclean(counter, columnNumber).Value = 5
        ElseIf MonthlyValuesUnclean(counter, columnNumber).Text = "Y" Then
            MonthlyValuesUnclean(counter, columnNumber).Value = 4
        ElseIf MonthlyValuesUnclean(counter, columnNumber).Text = "G" Then
            MonthlyValuesUnclean(counter, columnNumber).Value = 3
        ElseIf MonthlyValuesUnclean(counter, columnNumber).Text = "?" Then
            MonthlyValuesUnclean(counter, columnNumber).Value = 2
        Else
            MonthlyValuesUnclean(counter, columnNumber).Value = 1
        End If

    Next counter
Next columnNumber

1 个答案:

答案 0 :(得分:1)

我要做的是取一系列单元格并将它们放入数组中。

好吧,这就是我的想法,但你实际上并没有这样做。您已经定义了一系列范围对象(不是您想要的),并且您可能正确地(但不必要地)对该数组进行了尺寸标注。

在此,我们将首先定义并分配范围变量(monthlyValuesRange)。然后,我们将范围的.Value数组分配给数组变量(MonthlyValuesUnclean)。然后,我们可以处理该数组,最后将这些值放回到工作表中。

Sub Test()
    Dim MonthlyValuesUnclean As Variant
    Dim CodeCountOne As Long
    Dim monthlyValuesRange As Range

    CodeCountOne = Application.CountA(Range("A:A")) 'Counts Total Number of Codes Before Clean

    'Define your range variable
    Set monthlyValuesRange = Range("A1:C" & CodeCountOne)

    'Assigns the range's value array to the MonthlyValuesUnclean array variable:
    MonthlyValuesUnclean = monthlyValuesRange.Value

    For columnNumber = 1 To 3
        For counter = 1 To CodeCountOne
        '## I find Select statement easier to work with:
        Select Case UCase(MonthlyValuesUnclean(counter, columnNumber))
            Case "R"
                MonthlyValuesUnclean(counter, columnNumber) = 5

            Case "Y"
                MonthlyValuesUnclean(counter, columnNumber) = 4

            Case "G"
                MonthlyValuesUnclean(counter, columnNumber) = 3

            Case "?"
                MonthlyValuesUnclean(counter, columnNumber) = 2

            Case Else
                MonthlyValuesUnclean(counter, columnNumber) = 1
         End Select
        Next counter
    Next columnNumber

    'Now put the updated values in the worksheet
     monthlyValuesRange.Value = MonthlyValuesUnclean
End Sub

经测试&确认这是按预期工作的。之前:

enter image description here

后:

enter image description here

在VBE的本地化窗口中检查MonthlyValuesUnclean的示例:

enter image description here