1

我遇到了 Excel 宏的一些问题。我也在尝试将工作表的各个单元格中的值复制到一个数组中,以便稍后与其他工作表的单元格值进行比较。

但是,我被困在数组中以存储我试图分配给它的所有值。

下面是我完成的代码片段。

Sub singleEntry(suppRow As Integer)

Dim j As Integer
Dim myArray() As Variant
Dim a As Integer
Dim b As Integer
Dim c As Integer

Worksheets("Ind. Supp. Plan Time").Select
Cells(suppRow, "I").Select

For j = 9 To 13
    c = j - 8

ReDim myArray(5, 4) As Variant
myArray(c, 1) = c

'ReDim Preserve myArray(5, 4) As Variant
If Cells(suppRow, j).Value = "*" Then
    ReDim Preserve myArray(5, 4) As Variant
    'myArray(j - 8, 1) = j - 8
    myArray(j - 8, 2) = Cells(suppRow, "P").Value
    myArray(j - 8, 3) = Cells(suppRow, "Q").Value
    myArray(j - 8, 4) = Cells(suppRow, "R").Value
    MsgBox "array = {" & myArray(c - 1, 2) & "}"
Else
    ReDim Preserve myArray(5, 4) As Variant
    myArray(j - 8, 2) = "1"
    myArray(j - 8, 3) = "1"
    myArray(j - 8, 4) = "1"
    MsgBox "array(1,3) = {" & myArray(1, 3) & "}"
End If

Next j

ReDim Preserve myArray(5, 4) As Variant
'For a = 1 To 5
'    For b = 1 To 4
'        MsgBox "Array = {" & myArray(a, b) & "}"
'    Next b
'Next a

End Sub

我放入 MsgBox 查看执行代码的结果,我确定这些行按预期执行。如果我在分配一个值后立即打印数组的值,则打印的值是正确的。但是,现在我无法解决这个问题。

希望知道这个的人可以给我帮助。

非常感谢你!

4

1 回答 1

0

不知道为什么你不能检索值。我对此进行了测试,并且可以正常工作。

Sub singleEntry(suppRow As Integer)
    Dim arrStore(1 To 5, 1 To 4) As Variant, col As Integer, r As Integer, c As Integer

    Worksheets("Ind. Supp. Plan Time").Select

    For col = 9 To 13
        arrStore(col - 8, 1) = col - 8
        arrStore(col - 8, 2) = IIf(Cells(suppRow, col) = "*", Cells(suppRow, "P"), 1)
        arrStore(col - 8, 3) = IIf(Cells(suppRow, col) = "*", Cells(suppRow, "Q"), 1)
        arrStore(col - 8, 4) = IIf(Cells(suppRow, col) = "*", Cells(suppRow, "R"), 1)
    Next col

    For r = 1 To 5
        For c = 1 To 4
           Debug.Print arrStore(r, c)
        Next c
    Next r

End Sub

注意事项:

  • 鉴于您总是填充数组,因此无需ReDim. 这是多余的(而且很昂贵)
  • 我使用三元IIF语句来整理代码,即 if "*" then x else 1
  • 我认为您不需要该变量c,因此我已将其删除
  • 我在最后添加了一个简单的循环来打印出数组(这对我有用)

这能解决吗?

于 2012-11-18T14:31:41.700 回答