Declare and Set unknown number of variables as String

longbow2000

Board Regular
Joined
May 5, 2004
Messages
59
Office Version
  1. 365
Platform
  1. Windows
Good Day

I want to declare various strings, i.e., Str1 As String, St2, As String up to specific number (n), Str(n) As String



In my code I count the number of cells with value in it:

nrLinks = WorksheetFunction.CountA(ws.Columns(1))

'Using the returned value in a loop function to obtain details, then I would like to assign a StringName:

For i = 1 To nrLinks

wsTemp.Cells(i, 1) = Left(ws.Cells(i, 1), (Application.WorksheetFunction.Find("_", ws.Cells(i, 1), 1) - 1))

Dim “Str” & i As String (or Dim Str + i As String)? (not sure about correct coding)
Set "Str" & i As wsTemp.Cells(i, 1) ? (not sure about correct coding)

Next i


' Use Str1, Str2, to last Str(n) later in code



Thanks in advance
 

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
Hi,
you would declare your variable as an array & size it accordingly

example

VBA Code:
    Dim myStr()    As String
    Dim nrLinks    As Variant
    Dim i               As Long
    Dim ws           As Worksheet
    
    Set ws = ActiveSheet
    
    nrLinks = WorksheetFunction.CountA(ws.Columns(1))
    
    'size array
    ReDim myStr(1 To nrLinks)
    
    'populate array elements
    For i = 1 To nrLinks
    
        myStr(i) = ws.Cells(i, 2)
    
    Next i

Array elements can then be used as required in your code

Note I changed your variable name Str to myStr as Str as function name of the application & its use as variable best avoided

You can read more about arrays here: Using arrays (VBA)

Dave
 
Upvote 0
Solution

Forum statistics

Threads
1,215,364
Messages
6,124,507
Members
449,166
Latest member
hokjock

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top