vba工作表重命名_使用带有条件的VBA代码重命名工作表列表

2023-02-18 00:00:00 vba 工作 重命名

vba工作表重命名

Renaming of worksheets can be done manually, but it will look like a massive task if there are a lot of worksheets to be renamed and when we need to rename it based on some conditions or values.

重命名工作表可以手动完成,但是如果要重命名许多工作表以及需要根据某些条件或值重命名工作表,这将是一项艰巨的任务。

Today, I’m going to show how we can actually rename the worksheets based on conditions by writing some VBA codes.

今天,我将展示如何通过编写一些VBA代码,根据条件实际重命名工作表。

Create the fundamental

创造基础

Renaming the worksheet can be as easy as looking for a fixed value and then renaming it accordingly with another fixed value.

重命名工作表就像查找一个固定值,然后相应地使用另一个固定值重命名一样容易。

Worksheets("Sheet1").Name = "New Sheet Name" 

When we are trying to rename many worksheets, we can repeat to call the codes with minimal changes:

当我们尝试重命名许多工作表时,我们可以重复执行以最少的更改来调用代码:

Worksheets("Sheet1").Name = "New Sheet Name"
Worksheets("Sheet2").Name = "New Sheet Name (2)" 

Note: You must be careful when you trying to rename your worksheet:

注意:尝试重命名工作表时,必须小心:

1) Make sure the worksheet name you’re referring to exists in the current worksheet

1 )确保您要引用的工作表名称在当前工作表中存在

2) Make sure the new worksheet name doesn’t exist in the current worksheet

2 )确保新工作表名称在当前工作表中不存在

To better handle this, you can create a function like this:

为了更好地处理此问题,您可以创建如下函数:

Function getWorkSheet(ByVal WorkSheetName As String) As Worksheet
    On Error GoTo EH
    Set getWorkSheet = Worksheets(WorkSheetName)
    Exit Function
EH:
    Set getWorkSheet = Nothing
End Function

Function renameWorkSheet(ByRef ws As Worksheet, ByVal NewWsName As String) As Boolean
    On Error GoTo EH
    Debug.Print ws.Name & " to " & NewWsName
    If getWorkSheet(NewName) Is Nothing Then
        ws.Name = NewWsName
        renameWorkSheet = True
    Else
        'New Worksheet Name already exists
        renameWorkSheet = False
    End If
    Exit Function
EH:
    renameWorkSheet = False
End Function 

Function getWorkSheet will be used to look up if there’s an existing worksheet with the name that passes to that function. In this case, this function will return a worksheet object. Of course, you can customize your own codes to return as a Boolean instead, for example, but it’s all up to you how you design your code.

函数getWorkSheet将用于查找是否存在名称传递给该函数的现有工作表。 在这种情况下,此函数将返回一个工作表对象。 当然,例如,您可以自定义自己的代码以返回为布尔值,但是这完全取决于您如何设计代码。

Function renameWorkSheet will be used to handle the rename worksheet process. First, it checks if the worksheet exists before the code proceeds to rename it.

函数renameWorkSheet将用于处理重命名工作表过程。 首先,它在代码进行重命名之前检查工作表是否存在。

So, we can directly implement the rename process by using code like this:

因此,我们可以使用以下代码直接实现重命名过程:

renameWorkSheet Worksheets("Sheet1"), "New Sheet Name"
renameWorkSheet Worksheets("Sheet2"), "New Sheet Name (2)" 

which should rename the worksheets accordingly

应该相应地重命名工作表

So far so good, right?

到目前为止一切顺利,对吗?

Now, what we can do is to rename the worksheets based on a set of rules, by knowing or without knowing how many of worksheets in total we should be renaming.

现在,我们可以做的是基于一组规则来重命名工作表,方法是知道(或不知道)总共应该重命名多少个工作表。

To do that, I would think we can list out the requirements we needed, such as:

为此,我认为我们可以列出所需的要求,例如:

1) What to be compared, such as fixed values, or cell values, etc.

1 )要比较的内容,例如固定值或单元格值等。

2) The comparison method, such as exact match, partial match, or match by using start with, etc.

2 )比较方法,例如精确匹配,部分匹配或通过使用start with进行匹配等。

To address the above, I have come out with a  data structure like this:

为了解决上述问题,我提出了这样的数据结构:

Private Enum CompareMethod
    Exact = 1
    Within = 2
    StartWith = 3
End Enum

Private Enum ReadFrom
    Cell = 1
    FixedValue = 2
End Enum

Private Type WorkSheetSettings
    CompareKey As String
    CompareMethod As CompareMethod
    ReadFrom As ReadFrom
    ReplaceWith As String
    ReadFrom2 As ReadFrom
    ReplaceWith2 As String
    JoinString As String
End Type 

Enum is being used to define the possible values for our own defined type.

枚举被用来为我们自己定义的类型定义可能的值。

Type is being used to declare a user-defined type.

类型用于声明用户定义的类型。

In addition, we would need a function getNewWsName to generate the new worksheet name based on the options given above:

另外,我们将需要一个函数getNewWsName来基于上面给出的选项生成新的工作表名称:

Function getNewWsName(ByRef ws As Worksheet, ByRef config As WorkSheetSettings) As String
    If config.ReplaceWith <> "" Then
        If config.ReadFrom = Cell Then
            getNewWsName = ws.Range(config.ReplaceWith).Value
        Else
            getNewWsName = config.ReplaceWith
        End If
    End If
    If config.ReplaceWith2 <> "" Then
        If config.ReadFrom2 = Cell Then
            getNewWsName = getNewWsName & config.JoinString & ws.Range(config.ReplaceWith2).Value
        Else
            getNewWsName = getNewWsName & config.JoinString & config.ReplaceWith2
        End If
    End If
End Function 

Now, to rename “Sheet1” to “New Sheet Name“, we can implement this:

现在,要将“ Sheet1 ”重命名为“ New Sheet Name ”,我们可以实现以下功能:

    Dim NewWsName As String
    Dim ws As Worksheet
    Dim myConfig As WorkSheetSettings
    
    myConfig.CompareKey = "Sheet1"
    myConfig.CompareMethod = Exact
    myConfig.ReadFrom = FixedValue
    myConfig.ReplaceWith = "New Sheet Name"
    
    Set ws = getWorkSheet(myConfig.CompareKey)
    If Not ws Is Nothing Then
        NewWsName = getNewWsName(ws, myConfig)
        renameWorkSheet ws, NewWsName
    End If 

In the event that we would like to rename Sheet1 based on the cell value of Sheet1’s cell, A1, we can implement the same by using code:

如果我们想基于Sheet1的单元格A1的单元格值重命名Sheet1,我们可以使用以下代码来实现:

    Dim NewWsName As String
    Dim ws As Worksheet
    Dim myConfig As WorkSheetSettings
    
    myConfig.CompareKey = "Sheet1"
    myConfig.CompareMethod = Exact
    myConfig.ReadFrom = Cell
    myConfig.ReplaceWith = "A1"
   
    Set ws = getWorkSheet(myConfig.CompareKey)
    If Not ws Is Nothing Then
        NewWsName = getNewWsName(ws, myConfig)
        renameWorkSheet ws, NewWsName
    End If 

To replace multiple worksheets all together, we can simply declare the WorkSheetSettings as an array with the settings, like:

要一起替换多个工作表,我们可以简单地将WorkSheetSettings声明为具有设置的数组,例如:

    Dim NewWsName As String
    Dim ws As Worksheet
    Dim myConfig(1) As WorkSheetSettings
    
    myConfig(0).CompareKey = "Sheet1"
    myConfig(0).CompareMethod = Exact
    myConfig(0).ReadFrom = Cell
    myConfig(0).ReplaceWith = "A1"
    
    myConfig(1).CompareKey = "Sheet2"
    myConfig(1).CompareMethod = Exact
    myConfig(1).ReadFrom = FixedValue
    myConfig(1).ReplaceWith = "New Sheet Name (2)"
    
    For i = 0 To UBound(myConfig)
        Set ws = getWorkSheet(myConfig(i).CompareKey)
        If Not ws Is Nothing Then
            NewWsName = getNewWsName(ws, myConfig(i))
            renameWorkSheet ws, NewWsName
        End If
    Next 

You can try exploring the possible combinations by revisiting the rules:

您可以尝试通过重新访问规则来探索可能的组合:

1) What to be compared, such as fixed values, or cell values, etc.

1 )要比较的内容,例如固定值或单元格值等。

2) The comparison method, such as exact match, partial match, or match by using start with, etc.

2 )比较方法,例如精确匹配,部分匹配或通过使用start with进行匹配等。

Real Scenario Implementation

实际方案实施

Based on the question posted recently: Needs Help With Conditional Renaming for Several Tabs

基于最近发布的问题: 需要几个标签的条件重命名的帮助

For the 1st tab, the “Allocation” tab, I need to rename it as “Master_CellD28Value” which means that if Cell D28’s value is A123 – FIFO, the tab should be renamed to “Master_A123 – FIFO”.

对于第一个选项卡,即“分配”选项卡,我需要将其重命名为“ Master_CellD28Value”,这意味着如果单元格D28的值为A123-FIFO,则该选项卡应重命名为“ Master_A123-FIFO”。

For the 6th and 7th tab, the “ESD Trf Qty” and “EVNL Trf Qty” tabs, I need it to be renamed like this: The part before “ Trf Qty”_Cell C28’s value. For example, if EVNL Trf Qty tab’s cell C28 value is A123 – LIFO then the tab should be renamed to “EVNL_A123 – LIFO”

对于第6和第7个选项卡,“ ESD Trf数量”和“ EVNL Trf数量”选项卡,我需要像这样重命名:“ Trf数量” _Cell C28值之前的部分。 例如,如果“ EVNL Trf数量”选项卡的单元格C28值为A123-LIFO,则该选项卡应重命名为“ EVNL_A123-LIFO”

The tabs which are named “By Ctrn-EIN”, “By Ctrn-EMSB”, “By Ctrn-ETH”, “By Ctrn-EPC” and “By Ctry-IDC”, these need to be renamed to “CellE25Value_CellC28Value”. If Cell E25 Value’s is Canada and Cell C28’s Value is B987 -123 then the tab should be renamed to “Canada_B987 – 123”

名为“按Ctrn-EIN”,“按Ctrn-EMSB”,“按Ctrn-ETH”,“按Ctrn-EPC”和“按Ctry-IDC”的选项卡,这些选项卡需要重命名为“ CellE25Value_CellC28Value”。 如果单元格E25的值是加拿大,单元格C28的值是B987 -123,则该选项卡应重命名为“ Canada_B987-123”

As an error proofing method, the last tab, the subset list should be left alone.

作为防错方法,最后一个选项卡,子集列表应保留为空。

This actually can be done by simply changing the rules and apply the code below:

实际上,只需更改规则并应用以下代码即可完成此操作:

Sub RenameWorkSheets()
    Dim NewWsName As String
    Dim ArrPrefix(3) As WorkSheetSettings
    
    ArrPrefix(0).CompareKey = "Allocation"
    ArrPrefix(0).CompareMethod = Exact
    ArrPrefix(0).ReadFrom = FixedValue
    ArrPrefix(0).ReplaceWith = "Master_"
    ArrPrefix(0).ReadFrom2 = Cell
    ArrPrefix(0).ReplaceWith2 = "D28"
    
    ArrPrefix(1).CompareKey = "ESD "
    ArrPrefix(1).CompareMethod = StartWith
    ArrPrefix(1).ReadFrom = FixedValue
    ArrPrefix(1).ReplaceWith = "ESD_"
    ArrPrefix(1).ReadFrom2 = Cell
    ArrPrefix(1).ReplaceWith2 = "C28"
    
    ArrPrefix(2).CompareKey = "EVNL "
    ArrPrefix(2).CompareMethod = StartWith
    ArrPrefix(2).ReadFrom = FixedValue
    ArrPrefix(2).ReplaceWith = "EVNL_"
    ArrPrefix(2).ReadFrom2 = Cell
    ArrPrefix(2).ReplaceWith2 = "C28"
    
    ArrPrefix(3).CompareKey = "By "
    ArrPrefix(3).CompareMethod = StartWith
    ArrPrefix(3).ReadFrom = Cell
    ArrPrefix(3).ReplaceWith = "E25"
    ArrPrefix(3).ReadFrom2 = Cell
    ArrPrefix(3).ReplaceWith2 = "C28"
    ArrPrefix(3).JoinString = "_"
    
    Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
        For i = 0 To UBound(ArrPrefix)
            Select Case ArrPrefix(i).CompareMethod
            Case CompareMethod.Exact
                If ws.Name = ArrPrefix(i).CompareKey Then
                    NewWsName = getNewWsName(ws, ArrPrefix(i))
                    renameWorkSheet ws, NewWsName
                    Exit For
                End If
            Case CompareMethod.StartWith
                If Left(ws.Name, Len(ArrPrefix(i).CompareKey)) = ArrPrefix(i).CompareKey Then
                    NewWsName = getNewWsName(ws, ArrPrefix(i))
                    renameWorkSheet ws, NewWsName
                    Exit For
                End If
            Case CompareMethod.Within
                If InStr(ws.Name, ArrPrefix(i).CompareKey) > 0 Then
                    NewWsName = getNewWsName(ws, ArrPrefix(i))
                    renameWorkSheet ws, NewWsName
                    Exit For
                End If
            End Select
        Next
    Next
End Sub 

As you can see, the main code remains the same. Hence, minimal code changes are needed.

如您所见,主要代码保持不变。 因此,需要最少的代码更改。

Note:

注意:

In the case you see the worksheet name is not being renamed, there could be some possibilities:

如果您看到工作表名称未重命名,则可能存在一些可能性:

1) You provided an invalid sheet name that needs to be renamed

1 )您提供了一个无效的工作表名称,需要重命名

2) You provided an empty new sheet name

2 )您提供了一个空白的新工作表名称

3) You provided a new sheet name that is over the limited allowed in Excel (max allowed is 31 chars)

3 )您提供的新工作表名称超出了Excel中允许的限制(允许的最大字符数为31个字符)

4) You provided a new sheet name that already exists

4 )您提供了一个已经存在的新工作表名称

Well, we are done! And here is the complete code to share with you all:

好了,我们完成了! 以下是与大家共享的完整代码:

Private Enum CompareMethod
    Exact = 1
    Within = 2
    StartWith = 3
End Enum

Private Enum ReadFrom
    Cell = 1
    FixedValue = 2
End Enum

Private Type WorkSheetSettings
    CompareKey As String
    CompareMethod As CompareMethod
    ReadFrom As ReadFrom
    ReplaceWith As String
    ReadFrom2 As ReadFrom
    ReplaceWith2 As String
    JoinString As String
End Type

Sub RenameWorkSheets()
    Dim NewWsName As String
    Dim ArrPrefix(3) As WorkSheetSettings
   
    ArrPrefix(0).CompareKey = "Allocation"
    ArrPrefix(0).CompareMethod = Exact
    ArrPrefix(0).ReadFrom = FixedValue
    ArrPrefix(0).ReplaceWith = "Master_"
    ArrPrefix(0).ReadFrom2 = Cell
    ArrPrefix(0).ReplaceWith2 = "D28"
   
    ArrPrefix(1).CompareKey = "ESD "
    ArrPrefix(1).CompareMethod = StartWith
    ArrPrefix(1).ReadFrom = FixedValue
    ArrPrefix(1).ReplaceWith = "ESD_"
    ArrPrefix(1).ReadFrom2 = Cell
    ArrPrefix(1).ReplaceWith2 = "C28"
   
    ArrPrefix(2).CompareKey = "EVNL "
    ArrPrefix(2).CompareMethod = StartWith
    ArrPrefix(2).ReadFrom = FixedValue
    ArrPrefix(2).ReplaceWith = "EVNL_"
    ArrPrefix(2).ReadFrom2 = Cell
    ArrPrefix(2).ReplaceWith2 = "C28"
   
    ArrPrefix(3).CompareKey = "By "
    ArrPrefix(3).CompareMethod = StartWith
    ArrPrefix(3).ReadFrom = Cell
    ArrPrefix(3).ReplaceWith = "E25"
    ArrPrefix(3).ReadFrom2 = Cell
    ArrPrefix(3).ReplaceWith2 = "C28"
    ArrPrefix(3).JoinString = "_"
   
    Dim ws As Worksheet
   
    For Each ws In ActiveWorkbook.Worksheets
        For i = 0 To UBound(ArrPrefix)
            Select Case ArrPrefix(i).CompareMethod
            Case CompareMethod.Exact
                If ws.Name = ArrPrefix(i).CompareKey Then
                    NewWsName = getNewWsName(ws, ArrPrefix(i))
                    renameWorkSheet ws, NewWsName
                    Exit For
                End If
            Case CompareMethod.StartWith
                If Left(ws.Name, Len(ArrPrefix(i).CompareKey)) = ArrPrefix(i).CompareKey Then
                    NewWsName = getNewWsName(ws, ArrPrefix(i))
                    renameWorkSheet ws, NewWsName
                    Exit For
                End If
            Case CompareMethod.Within
                If InStr(ws.Name, ArrPrefix(i).CompareKey) > 0 Then
                    NewWsName = getNewWsName(ws, ArrPrefix(i))
                    renameWorkSheet ws, NewWsName
                    Exit For
                End If
            End Select
        Next
    Next
End Sub

Function getNewWsName(ByRef ws As Worksheet, ByRef config As WorkSheetSettings) As String
    If config.ReplaceWith <> "" Then
        If config.ReadFrom = Cell Then
            getNewWsName = ws.Range(config.ReplaceWith).Value
        Else
            getNewWsName = config.ReplaceWith
        End If
    End If
    If config.ReplaceWith2 <> "" Then
        If config.ReadFrom2 = Cell Then
            getNewWsName = getNewWsName & config.JoinString & ws.Range(config.ReplaceWith2).Value
        Else
            getNewWsName = getNewWsName & config.JoinString & config.ReplaceWith2
        End If
    End If
End Function

Function getWorkSheet(ByVal WorkSheetName As String) As Worksheet
    On Error GoTo EH
    Set getWorkSheet = Worksheets(WorkSheetName)
    Exit Function
EH:
    Set getWorkSheet = Nothing
End Function

Function renameWorkSheet(ByRef ws As Worksheet, ByVal NewWsName As String) As Boolean
    On Error GoTo EH
    Debug.Print ws.Name & " to " & NewWsName
    If getWorkSheet(NewName) Is Nothing Then
        ws.Name = NewWsName
        renameWorkSheet = True
    Else
        'New Worksheet Name already exists
        renameWorkSheet = False
    End If
    Exit Function
EH:
    renameWorkSheet = False
End Function 

What’s more?

更重要的是?

Last but not least, we can further enhance our code to include features such as:

最后但并非最不重要的一点是,我们可以进一步增强代码以包括以下功能:

  • Put the color options to worksheet’s tab

    将颜色选项放入工作表的选项卡

  • Sort the worksheets according to certain orders

    根据某些顺序对工作表进行排序

  • Split the content of a worksheet into multiple worksheets

    将工作表的内容拆分为多个工作表

  • Merge the content of worksheets into a single worksheet

    将工作表的内容合并到一个工作表中

This I think we can discuss that in future tutorials.

我想我们可以在以后的教程中对此进行讨论。

I hope you found this article useful. You are encouraged to ask questions, report any bugs or make any other comments about it below.

希望本文对您有所帮助。 鼓励您在下面提出问题,报告任何错误或对此作出任何其他评论。

Note: If you need further “Support” about this topic, please consider using the Ask a Question feature of Experts Exchange. I monitor questions asked and would be pleased to provide any additional support required in questions asked in this manner, along with other EE experts…

注意 :如果您需要有关此主题的更多“支持”,请考虑使用Experts Exchange 的“提问”功能。 我会监督提出的问题,并很高兴与其他电子工程师一起提供以这种方式提出的问题所需的任何其他支持…

Please do not forget to press the “Thumb’s Up” button if you think this article was helpful and valuable for EE members.  It also provides me with positive feedback. Thank you!

如果您认为本文对EE成员有用且有价值,请不要忘记按“ Thumb’s Up”按钮。 它还为我提供了积极的反馈。 谢谢!

《vba工作表重命名_使用带有条件的VBA代码重命名工作表列表》

翻译自: https://www.experts-exchange.com/articles/33507/Rename-a-list-of-worksheets-using-VBA-codes-with-conditions.html

vba工作表重命名

    原文作者:cunchi8090
    原文地址: https://blog.csdn.net/cunchi8090/article/details/107495604
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章