1

I am trying (in VBA) to define a large number of string variables. The brute force would be :

Dim Port1 as String Dim Port2 as String etc…

Unpleasant for say 100 variables. There must be a more intelligent solution. I have tried :

Dim n As Integer For n = 1 To 100 Dim "Port" & n as String Next n

and variations of it without success. I would greatly appreciate if someone could point me in the right direction or share an example.

2
  • 2
    Look into arrays, it will allow you to load it up with a loop. Commented Feb 10, 2016 at 17:52
  • 1
    What about using array ? : excel-easy.com/vba/array.html Commented Feb 10, 2016 at 17:52

1 Answer 1

7

Arrays do exactly this! See this example:

Dim Port(1 to 100) As String
Dim i As Long

Port(1) = "String"
For i = 2 to 100
    Port(i) = "String " & i
Next i

It sets Port(1), the first array element to the word "String". Everything else Port(2) and on, contain "String 2", "String 3", etc. Up to Port(100).

I hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you AndASM, I will try and it sounds the right way to go. I ignored there were arrays in VBA (very stupid of me…!!!) Thanks.

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.