Search code examples
arraysexcelvbadatediff

Why is my array in VBA not populating all of the values?


This is my first post. I have been using VBA for a month now, and I am trying to populate an array with dates based on a user defined range. For example, the user will input: 05/01/2001 - 05/21/2001. There for I am trying to populate an array with all of the days from start to end, with this example it will be 21 dates. When I print out the array, I am only getting the odd days, and not the even days. Can anyone help with this? Thanks!

I am usind the DateDiff() function to get the number of days between the start and end dates to determine the number of dates I have to include inside of the array.

temp_csv_file_count is the number of values inside the array, input_start_date and input_end_date are strings, ignore the state, that has to do with something else.

temp_csv_file_count = DateDiff("d", input_start_date, input_end_date)
temp_csv_file_count = temp_csv_file_count + 1

Dim temp_date() As String
ReDim temp_date(0 To temp_csv_file_count) As String

Dim i As Integer

For i = 0 To temp_csv_file_count
        temp_date(i) = DateAdd("d", i, input_start_date)
        i = i + 1
Next i


msg = "File Count: " & temp_csv_file_count & ", State: " & temp_state
MsgBox msg

Dim array_contents As String
Dim j As Integer

For j = 0 To temp_csv_file_count
        array_contents = array_contents + temp_date(j) + vbNewLine
Next j

MsgBox "the values of my dynamic array are: " & vbNewLine & array_contents

Actual: 05/01/2001, 05/03/2001, 05/05/2001, 05/07/2001, 05/09/2001, 05/11/2001, 05/13/2001, 05/15/2001, 05/17/2001, 05/19/2001, 05/21/2001


Solution

  • For i = 0 To temp_csv_file_count
        temp_date(i) = DateAdd("d", i, input_start_date)
        'i = i + 1 'THIS IS WHY
    Next i
    

    A for loop will iterate 1 at a time, unless specified in the Step (you haven't listed the step, so it assumes 1), you are telling it to add 1 before the loop itself iterates (via Next i).

    For i = 0 To temp_csv_file_count Step 1 'added the step to ensure it is understood
        temp_date(i) = DateAdd("d", i, input_start_date)
    Next i