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”按钮。 它还为我提供了积极的反馈。 谢谢!

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

vba工作表重命名

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

  1. python文件批量重命名以数字~n的方式重命名_利用Python对文件进行批量重命名

    最近几天工作的内容是对40个项目进行考核,每个项目都需要一个考核评分表,已经有了项目的列表. 如果用常规的方法,需要复制40个文件,并逐个修改,不光工作量大,也容易出错,后期修改也不方便. 于是想到了 ...

  2. mysql创建表属性引_【学习之Mysql数据库】mysql数据库创建表的属性详解

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 MySQL中create table语句的基本语法是: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name ...

  3. basefont.createfont设置表单字体_《Flask 入门教程》第 7 章:表单

    在 HTML 页面里,我们需要编写表单来获取用户输入.一个典型的表单如下所示: <form method="post"> <!-- 指定提交方法为 POST -- ...

  4. python 复制文件并重命名_好书推荐 | Python 如此神奇,让繁琐工作自动化

    优质文章,第一时间送达! Python 如此神奇,让繁琐工作自动化 编程的威力 如今,人们面临的大多数任务都可以通过编写计算机软件来完成. Al Sweigart 的室友曾经只花了几个小时,就写出了一 ...

  5. 算法训练营 重编码_编码训练营后十四天如何找到工作

    算法训练营 重编码 Fourteen days after I graduated from my coding bootcamp, I had a job offer. Two weeks afte ...

  6. sql server重命名_在Linux上SQL Server中重命名逻辑和物理文件名

    sql server重命名 Each database in SQL Server contains at least two files i.e. Data file (*.mdf) and log ...

  7. 不同表结构数据迁移_数据结构:哈希 哈希函数 哈希表

    写在前面 希望你们看了能够有所收获,同时觉得不错的朋友可以点赞和关注下我,以后还会有更多精选文章分享给大家!大家可以关注一下java提升专栏 java提升​zhuanlan.zhihu.com 什么是 ...

  8. mysql不可重复读和重复读_脏读、幻读、不可重复读的区别是什么

    脏读.幻读.不可重复读的区别:1.脏读就是指当一个事务正在访问数据,并且对数据进行了修改:2.不可重复读是指在一个事务内,多次读同一数据:3.幻读是指当事务不是独立执行时发生的一种现象. [相关学习推 ...

  9. 为什么要避免不可重复读_脏读、幻读和不可重复读?为啥?

    前言: 一致性是指在事务开始之前和事务结束以后,数据库的完整性约束没有被破坏.这是说数据库事务不能破坏关系数据的完整性以及业务逻辑上的一致性. 例子: 对银行转帐事务,不管事务成功还是失败,应该保证事 ...

最新文章

  1. mysql 函数的参数_MySQL中的数值函数
  2. linux c 信号量简介
  3. python【蓝桥杯vip练习题库】ADV-172身份证排序
  4. git 删除本地仓库中的分支_git常用命令行 新建分支 删除分支 提交
  5. 【Linux】目录中 / 和 ~ 的区别
  6. 【Vue.js】iconfont中unicode引用和unicode引用失败,无法显示icon
  7. CDN原理 CDN技术是什么
  8. 人人商城小程序昵称变成了“微信用户”头像也不显示?getUserInfo换成getUserProfile
  9. 偏执的iOS逆向研究员:收集全版本的macOS iOS+越狱+内核调试
  10. 实训六 思科路由器配置静态路由
  11. 谈谈我对服务网格的理解
  12. 人脸检测——UnitBox
  13. Excel 美化要点
  14. excel自动恢复文档被关闭或者误删除
  15. Shiro 授权(权限)
  16. navicat连接服务器mysql,mysql外网连接
  17. DRV8301驱动芯片BUCK电路设计
  18. Linux之pstree命令
  19. 深入浅出TCP协议,为什么需要TCP协议?
  20. 网站推广120种实用方法系列连载

热门文章

  1. 杰理之通话远端手机听到电流声或高频干扰声常见分析方法【篇】
  2. P5.js创意编程之自我介绍
  3. launchctl定时任务
  4. 真全面屏 鸿蒙OS2.0 5000mAh,华为P50概念美图:2K微曲屏+鸿蒙OS系统+5000mAh
  5. gitlab4j 关于不安全SSL证书的解决
  6. VMware虚拟机快照
  7. 1.7-22:紧急措施
  8. C语言——万年历打印(详细易懂)
  9. Java、JSP二手手机收售系统
  10. python 读取合并单元格_python使用xlrd读取合并单元格