The Problem (Q-score 17, ranked #17th of 95 in the VBA Core archive)
The scenario as originally posted in 2011
I need to add the var in array
Public Sub Testprog()
Dim test As Variant
Dim iCounter As Integer
If test = Empty Then
iCounter = 0
test(iCounter) = "test"
Else
iCounter = UBound(test)
End If
End Sub
Getting error at test(iCounter) = "test"
Please suggest some solution
Why the Win32 API declaration is fragile here
This problem involves a Declare statement, which means 32-bit vs 64-bit compatibility is in play. Office 64-bit requires the PtrSafe keyword and LongPtr data types for any handles — the most common root cause of the exact symptom described.
The Verified Solution — strong answer (top 25 %%) (+25)
Verbal answer — walkthrough without a code block
Note: the verified answer is a prose walkthrough. If you need a runnable sample, check VBA Core entries ranked in the top 10 of the same archive.
Generally, you should declare variables of a specific type, rather than Variant. In this example, the test variable should be of type String.
And, because it’s an array, you need to indicate that specifically when you declare the variable. There are two ways of declaring array variables:
-
If you know the size of the array (the number of elements that it should contain) when you write the program, you can specify that number in parentheses in the declaration:
Dim test(1) As String 'declares an array with 2 elements that holds stringsThis type of array is referred to as a static array, as its size is fixed, or static.
-
If you do not know the size of the array when you write the application, you can use a dynamic array. A dynamic array is one whose size is not specified in the declaration (
Dimstatement), but rather is determined later during the execution of the program using theReDimstatement. For example:Dim test() As String Dim arraySize As Integer ' Code to do other things, like calculate the size required for the array ' ... arraySize = 5 ReDim test(arraySize) 'size the array to the value of the arraySize variable
When to Use It — vintage (14+ years old, pre-2013)
Ranked #17th in its category — specialized fit
This pattern sits in the 80% tail relative to the top answer. Reach for it when your scenario closely matches the question title; otherwise browse the VBA Core archive for a higher-consensus alternative.
What changed between 2011 and 2026
The answer is 15 years old. The VBA Core object model has been stable across Office 2013, 2016, 2019, 2021, 365, and 2024/2026 LTSC, so the pattern still compiles. Changes that might affect you: 64-bit API declarations (use PtrSafe), blocked macros in downloaded files (Mark-of-the-Web), and the shift toward Office Scripts for web-first workflows.