简体   繁体   中英

Index number/worksheet name confusion with variables when worksheet names are numerical

I might have found a novel problem! I'm trying to select worksheets based on the name of the worksheet, using a variable for the name since this is all part of a loop. But I run into trouble when the worksheet's name is a number, since if I have, say, name = 5, then Worksheets(name) gives me the index number 5 worksheet and Worksheets("name") of course looks for a worksheet named "name".

I could do a workaround with adding a letter to each worksheet's name so it's not treated as a number, and then removing those letters afterwards, but is there a better way?

Sub RenameFiles()
Dim source, old_filename, old_tab, new_filename As String
Dim i As Integer
source = Range("path").Value
For i = 1 To Range("total_file_number").Value
    old_filename = Worksheets("Import and combine").Cells(3 + i, 2).Value
    old_tab = Worksheets("Import and combine").Cells(3 + i, 3).Value
    new_filename = Worksheets(old_tab).Cells(1, 1).Value 'If old_tab is a number, VBA treats Worksheets(old_tab) as looking up a worksheet by index number rather than name
    If Left(Worksheets(old_tab).Cells(1, 1).Value, 1) = "*" Then new_filename = Right(new_filename, Len(new_filename) - 2) 'removes asterisk from name
    new_filename = Replace(new_filename, ">", "") 'removes > from name, since > can't be used in file names
    Worksheets(old_tab).Name = new_filename
    Worksheets("Import and combine").Cells(3 + i, 3).Value = new_filename
    Name source & "\" & old_filename As source & "\" & new_filename
Next i
End Sub

Your problem is caused by this line:

Dim source, old_filename, old_tab, new_filename As String

...though it does not manifest itself until you attempt to access the Worksheets collection.

This is a very common mistake. The ONLY variable in the above line that is of type String is the last one. Each of the others is of type Variant.

When assigning to the variant old_tab any numerical value will be stored as a number, not a string. And the problem with that is that the Worksheets collection needs a string value as a key to return the correct worksheet.

If each of the variables in the above line is supposed to be of type String then do this:

Dim source As String, old_filename As String, old_tab As String, new_filename As String

...and now that old-tab is a String, it's value will work properly as a key to the Worksheets collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM