简体   繁体   English

如何遍历所有工作表并根据活动工作表单元格值重命名?

[英]How do I loop through all sheets and rename based on the active sheet cell value?

I am trying to write a macro that will look through all sheets in the workbook, and if a sheet name contains "blank", to rename that sheet with the value in cell C1.我正在尝试编写一个宏来查看工作簿中的所有工作表,如果工作表名称包含“空白”,则使用单元格 C1 中的值重命名该工作表。

Here is what I have so far:这是我到目前为止所拥有的:


Sub Rename()

Dim ws As Worksheet
Dim sheetBlank As Worksheet
Set sheetBlank = ActiveWorkbook.ActiveSheet
Dim nameCell As Range
Set nameCell = ActiveSheet.Range("C1")
    
For Each ws In Sheets
    If sheetBlank.Name Like "*blank*" Then
    sheetBlank.Name = nameCell.Value
    End If
Next ws

End Sub

Now, this does rename the first active sheet, but it is not making any changes to the rest of them.现在,这确实重命名了第一个活动工作表,但不会对其余工作表进行任何更改。 What am I doing wrong?我究竟做错了什么?

You're referring to the wrong worksheet:您指的是错误的工作表:

Sub Rename()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name Like "*blank*" Then
            ws.Name = ws.Range("C1").Value
        End If
    Next ws
End Sub

You set your objects outside the loop and never touch them again.你将你的对象设置在循环之外,永远不要再碰它们。 If you're going to use "ActiveSheet" you need to .Activate each sheet in order to work, but that's not a good approach since your iterator (ws) represents the sheet object.如果您打算使用“ActiveSheet”,您需要.Activate每个工作表才能工作,但这不是一个好方法,因为您的迭代器 (ws) 代表工作表对象。

Public Sub Rename()
    Dim Ws As Worksheet
    
    For Each Ws In Worksheets
        If InStr(1, Ws.Name, "blank", vbTextCompare) > 0 Then _
            Ws.Name = Ws.Range("C1").Value2
    Next Ws
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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