3

I am getting a blank message box for an array which should automatically have and display the following values:

00:00:00

01:00:00

02:00:00 and so on...

Here is my code

Dim i As Integer
i = 0

Dim sampleArr(0 To 24) As Variant
Dim a As Integer
a = 0

Do Until i > 23

    sampleArr(a) = i & ":00:00"
    a = a + 1
    i = i + 1

    MsgBox sampleArr(a)
Loop

Please tell me what's wrong with this code

1
  • 3
    You are advancing a before using it so you are actually displaying the next blank array element. Commented Feb 23, 2018 at 9:28

3 Answers 3

4

You update the value of sampleArr(a), then increment a. So to get the just-updated value you need to use the pre-incremented value: a-1.

MsgBox sampleArr(a-1)
Sign up to request clarification or add additional context in comments.

Comments

3

Put the Msgbox first before you increment a and i.

MsgBox sampleArr(a)
a = a + 1
i = i + 1 

Comments

1

It's not entirely clear what you're trying to achieve here, (especially with a and i being identical. Presumably the msgbox is only actually in there to prove you've created the array correctly and will be removed later?

That said, as everyone is pointing out, you're incrementing your pointer before displaying the entry. The simplest way to fix that is to put the display line in immediately after creating the element.

I've also formatted i in order to produce the exact output you've requested.

Also, I suspect your array only needs to go 0 To 23 if this is some kind of time selector?

So, fixing your issue looks like:

Dim i As Integer
i = 0

Dim sampleArr(0 To 23) As Variant
Dim a As Integer
a = 0

Do Until i > 23

    sampleArr(a) = Format(i, "00") & ":00:00"
    MsgBox sampleArr(a)

    a = a + 1
    i = i + 1

Loop

However, you could just do the following:

Dim i As Integer
Dim sampleArr(0 To 23) As Variant
For i = 0 To 23
    sampleArr(a) = Format(i, "00") & ":00:00"
    MsgBox sampleArr(a)
Next

Beyond this, if you want to store the values in the array as TIME rather than a text representation of the time (useful for calculations etc.) then replace the sampleArr line with

sampleArr(a) = TimeSerial(i, 0, 0)

2 Comments

You are right, this is a time selector for a workbook covering a single day of data and as you've said, the message box is just there to prove that the array is working properly. However, I only need to have this loop until 23:00:00 since 24:00:00 is already equal to 0:00:00. This array will later be used for filtering, searching and to be an input value for a cell therefore I thought it would be better for it to be a String data type.
In that case, I'd suggest just using the For.. Next loop version as it's all you seem to need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.