2

I have an excel macro-enabled workbook that has 5 sheets. One of these sheets is named "NC" and one is named "SC". I have part of the code which adds dates to these sheets' names.

Sheets("NC").Name = "NC" & Replace(Date, "/", "-") Sheets("SC").Name = "SC" & Replace(Date, "/", "-")

Then later on if the reset button is clicked, I made a code to switch them back to previous "NC" and "SC" names but this is where I get the problem.

Sheets(2).Name = "NC" Sheets(3).Name = "SC"

Sheets(2).Name = "NC" works fine Sheets(3).Name = "SC" however, renames Sheet(4) instead

I thought these sheet codes or sheet numbers don't change no matter how you rearrange or reorder your sheet tabs. I don't understand why it accurately renamed Sheets(2) but not Sheets(3). Look at my project explorer below, it renames Sheets(4) instead from "NCToday" to "SC". Sheets(3) is showing "SC" in the picture but because this was manually reset but you can see the arrangement, the code Sheets(3).Name = "SC" SHOULD NOT have renamed Sheets(4) from "NCToday" to "SC".

Sheet List

4

3 回答 3

2

Sheet(3) 不一定表示 sheet3

例子: 在此处输入图像描述

如果我在即时窗口中键入?worksheets(1).name,我会得到以下结果:

表 2

请注意,系统会查看 excel 电子表格(Sheet2、Sheet1、Sheet3)上的工作表顺序,而不是 VBA 项目中的顺序(Sheet1、Sheet2、Sheet3)

要重命名工作表,您可能需要颠倒最初用于重命名它们的方法:

Sheets("SC" & Replace(Date, "/", "-")).Name = "SC"
于 2013-06-05T19:08:11.743 回答
0

有很多方法可以引用工作表。

使用

Sheets(number).Name 

'this will print all the names in the Sheets(i) order
for i = 1 to Sheets.count
    debug.pring sheets(i).name & " at index " & i
next i

number从左到右重命名工作簿中索引处的工作表。

使用

Sheet2.name = "NC"

将重命名资源管理器Sheet2中显示的 VBA 对象。

我怀疑你想做:

Sheet2.Name = "NC" 
Sheet3.Name = "SC"
于 2013-06-05T19:02:42.913 回答
0

您可能会使用 Like 选项在重命名之前比较工作表名称?

Dim s as Worksheet
For each s in Worksheets

    if s.Name like "NC*" and not s.Name = "NCToday" then
         s.Name = "NC"
    end if

next

这可以解决您的页面洗牌而不必诉诸“不要重新洗牌评论”?

像这样的评论很容易被误解,并且可能会让你的代码在某个阶段遇到麻烦和错误。

最好尝试一下,万无一失!

祝你好运 !

干杯!

于 2015-10-02T13:27:37.593 回答