我可能發現了一個新問題!我試圖選擇基於工作表名稱的工作表,使用變量作爲名稱,因爲這是循環的一部分。但是當工作表的名字是一個數字時,我遇到了麻煩,因爲如果我有,例如name = 5,那麼Worksheets(name)給我索引號5工作表和工作表(「name」)當然會查找一個名爲工作表「名稱」。工作表名稱爲數字時,索引號/工作表名稱與變量混淆
我可以做一個解決方法,爲每個工作表的名稱添加一個字母,以便它不被視爲數字,然後刪除這些字母,但有沒有更好的方法?
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
使用'cstr(name)'。名稱是變量。它會將數字更改爲字符串。 –