Entering data into arrays

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Folks,

I have a set of data like this:

1 Dave
3 Matt
2 Bill
4 Steve

I wanted to enter this data into an array, and assign it an address within
that array based on the number associated with each name. Hence 1 = Dave, 2 =
Bill etc. However the output seems to miss out the second data point. You end
up with:

1 Dave
2
3 Matt
4 Steve

Does data-entry into an array in VBA have to be sequential? The code I was
using was:

Sub test()
Dim testname(4)

For i = 1 To 4

testname(Cells(i, 1).Value) = Cells(i, 2).Value
Cells(i, 3).Value = testname(i)

Next i

End Sub

With the data in columns A and B in the spreadsheet. Appreciate it if
someone can spot the problem.

Cheers,

Matt
 
Your array is populated just fine. Your issue is with when you try to write
the values. The second array item is not populated until your counter is at
3. Problem is you tried to write it at 2 before it was populated... try
this...

Sub test()
Dim testname(4) As String
Dim i As Integer

For i = 1 To 4
testname(Cells(i, 1).Value) = Cells(i, 2).Value
Next i

For i = 1 To 4
Cells(i, 3).Value = testname(i)
Next i
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top