Domanda

I met with some problem with Excel Macro. I am trying too copy values from various cells of a worksheet into an array for use of comparing with other worksheet's cell value later.

However, I am stuck at the array to store all the value I am trying to assign to it.

Below is the code piece I have done.

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

I put in MsgBox to view the result of executing the code, I am sure the lines are executed as expected. If I print the value of the array straight away after assign one value to it, the value printed is correct. However, now I can't solve this problem.

Hopefully anyone know this can give me a help.

Thank you very much!

È stato utile?

Soluzione

Not sure why you can't retrieve values. I tested this and it works.

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

Points to note:

  • Given that you always fill the array there is no need to ReDim. It's redundant (and expensive)
  • I've used the ternary IIF statement to tidy up the code i.e. if "*" then x else 1
  • I don't think you need the variable c so I've removed it
  • I've added a simple loop at the end to print out the array (which works for me)

Does this solve it?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top