[英]Excel VBA: Change each sheet name to cell A1 value in each sheet
I have a code that is able to rename the active sheet (in this case, sheet 1) to the value in the A1 cell of the active sheet.我有一个代码可以将活动工作表(在本例中为工作表 1)重命名为活动工作表 A1 单元格中的值。 I'd like to write a function to be able to do this for every sheet in the Excel workbook.
我想编写一个函数,以便能够为 Excel 工作簿中的每个工作表执行此操作。 Where sheet 1 name will be the value of cell A1 on sheet 1, sheet 2 name will be the value of cell A1 on sheet 2, and so on.
其中工作表 1 名称将是工作表 1 上单元格 A1 的值,工作表 2 名称将是工作表 2 上单元格 A1 的值,依此类推。
Is it as simple as counting the number of sheets in the workbook and adding this to a range Worksheets(1:TotalCount)?是否像计算工作簿中的工作表数量并将其添加到范围工作表(1:TotalCount)一样简单?
Sub RenameSheet()
Worksheets(1).Select
Range("A1").Select
ActiveSheet.Name = ActiveCell.Value
End Sub
As BigBen says, you need a loop to through each sheet.正如 BigBen 所说,您需要一个循环来遍历每张纸。 Simplest way is to use the collection of Worksheet objects.
最简单的方法是使用 Worksheet 对象的集合。 Best to check the cell "A1" actually has something in it, otherwise you will get an error.
最好检查单元格“A1”中是否真的有东西,否则你会得到一个错误。 Try this:
尝试这个:
Option Explicit
Sub RenameSheets()
Dim ws As Worksheet
Dim strName As String
For Each ws In ActiveWorkbook.Worksheets
strName = ws.Range("A1").Value
If Len(strName) > 0 Then
ws.Name = strName
End If
Next ws
End Sub
You should probably also put in checks that the name hasn't already been used.您可能还应该检查该名称尚未被使用。 Excel wont like you having two sheets with the same name.
Excel 不会喜欢你有两张同名的工作表。 Top Excel Fact: you can't call a worksheet "History" ...
热门 Excel 事实:您不能将工作表称为“历史记录”...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.