Excel 2010 VBA - Use Value of variable as another

2019-08-05 19:19发布

This is a practice I follow while writing VBA code. I usually set worksheet names without spaces into variable names. For example I have a workbook with 3 worksheets with following names

1 - Control

2 - 60 W Status

3 - 60 W Status Pvt Tbl

I usually set worksheets names as worksheet variables in the following way:

Set wb = thisworkbook    
Set wsControl = wb.sheets("Control")
Set ws60WStatus = wb.sheets("60 W Status")    
Set ws60WStatusPvtTbl = wb.sheets("60 W Status Pvt Tbl")

Now I want to make this dynamic meaning my code should loop through all the worksheets in a workbook and store the worksheet names without spaces into variable names like ws*

So I have the following code so far:

Sub GetwsNames()
Set wb = thisworkbook
Dim wsNames()
i = 0 
'Loop through the workbook and store the names as wsName in an array
For each ws in worksheets
    Redim Preserve wsNames(i)
    Var1 = ws.Name
    Var2 = Replace(ws.Name," ", "")
    Var3 = "ws" & Var2
    wsNames(i) = Var3
    i = i + 1
Next

'Loop through array wsNames() and assign each element to corresponding workbook names
'For example
'Set wsControl = wb.sheets("Control")
'Set ws60WStatus = wb.Sheets("60 W Status")
'Set ws60WStatusPvtTbl = wb.sheets("60 W Status Pvt Tbl")

End Sub

I would like to know if there is any way to achieve this. Can we use value of a variable as another variable?

1条回答
We Are One
2楼-- · 2019-08-05 19:21

You can already reference sheets by name from the worksheets collection.

Worksheets("Sheet 1")

If you instead want to reference them by your modified names, creating an array or dictionary will work great. I suggest using a dictionary. It will allow you to reference items by key. In this example I use the modified name as the key and use the worksheet object as the item.

Dim myWorksheets As Scripting.Dictionary
Set myWorksheets = New Scripting.Dictionary
Dim ws As worksheet
For Each ws In ThisWorkbook.Worksheets
    Dim modifiedName As String
    modifiedName = "ws" & Replace(ws.Name, " ", "")
    myWorksheets.Add modifiedName, ws
Next
'You can now reference the worksheets by the modified names, through the dictionary
myWorksheets("wsControl").Cells(1, 1) = "Hi"
myWorksheets("ws60WStatus").Cells(1, 1) = "there"
myWorksheets("ws60WStatusPvtTbl").Cells(1, 1) = "world."

Note that you will need to add a reference to MS Scripting runtime in order to use dictionaries. To add the reference, go to Tools->References and check its box.

查看更多
登录 后发表回答