【问题标题】:Index number/worksheet name confusion with variables when worksheet names are numerical当工作表名称为数字时,索引号/工作表名称与变量混淆
【发布时间】:2015-11-18 16:06:33
【问题描述】:

我可能发现了一个新问题!我正在尝试根据工作表的名称选择工作表,并使用变量作为名称,因为这都是循环的一部分。但是当工作表的名称是一个数字时我会遇到麻烦,因为如果我有,比如说,name = 5,那么 Worksheets(name) 给我索引号 5 的工作表和 Worksheets("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)。名称为变量。它会将数字更改为字符串。

标签: excel vba naming worksheet


【解决方案1】:

你的问题是由这行引起的:

Dim source, old_filename, old_tab, new_filename As String

...尽管它在您尝试访问 Worksheets 集合之前不会显示出来。

这是一个非常常见的错误。上一行中唯一一个 String 类型的变量是最后一个。其他每个都是 Variant 类型。

当分配给变量old_tab 时,任何数值都将存储为数字,而不是字符串。问题在于 Worksheets 集合需要一个字符串值作为返回正确工作表的键。

如果上面一行中的每个变量都应该是字符串类型,那么这样做:

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

...现在 old-tab 是一个字符串,它的值将作为 Worksheets 集合的键正常工作。

【讨论】:

  • 我还以为我发现了一些新东西。谢谢,这正是问题所在!
猜你喜欢
  • 2019-05-10
  • 2012-08-22
  • 2019-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多