vba - Excel VBA - 从另一个工作簿中的新名称的col重命名所有工作表
问题描述
这个问题与使用 VBA 从列表中重命名多个工作表有点相似,但是差异太大,无法从该问题中得到答案。
我将经常需要重命名各种传入工作簿中的数十个工作表。
我希望通过首先将所有工作表名称复制到 secondWorkbook.sheets(1) colA 来重命名所有工作表,在 ColB 中手动创建新名称,然后运行第二个宏来更新 originalWorkbook 中的名称。
我被困在第二个宏上,但将在下面提供两个宏。如果有人有更短/更好的方式来编写这些宏,我会全神贯注。
第一个宏 - 将所有工作表名称复制到新的 workbook.sheet(1).colA 中。这有效,并使用 ColA 中的选项卡名称创建了一个新的未保存工作簿
Sub GrabAllTabNamesIntoTempWorkbookColA()
Dim tst, tmp, allTabNames As String
Dim i, cnt, cnt2 As Long
Dim wb, wbTmp As Workbook, xWs, ws1 As Worksheet
Dim arrOldNames, arrNewNames As Variant
ReDim arrOldNames(999)
cnt = 0
With ActiveWorkbook
For Each xWs In .Worksheets
If xWs.Visible = xlSheetVisible Then
arrOldNames(cnt) = xWs.Name
cnt = cnt + 1
End If
Next
End With
ReDim Preserve arrOldNames(cnt - 1)
cnt2 = 1
Set wbTmp = Workbooks.Add
Set ws1 = wbTmp.Sheets(1)
For i = 1 To cnt
ws1.Range("A" & i).Value = arrOldNames(i - 1)
Next
MsgBox "Done. Copied " & cnt & " tab names."
End Sub
这是我坚持的宏。两个工作簿都在屏幕上打开,我不介意编辑宏来提供工作簿名称。不确定如何引用名称为“Book4 - Microsoft Excel”的未保存工作簿,因此我一直将其保存为 Temp.xlsx 并将其引用为namesWb。带有要重命名的选项卡的工作簿被引用为targetWb
Sub RenameAllTabsFromColAInTempWorkbook()
Dim namesWb, targetWb As Workbook
Dim colA, colB As Variant
Set namesWb = Windows("Temp.xlsx")
Set targetWb = ActiveWorkbook
ReDim colA(999), colB(999)
cnt = 0
With namesWb
Sheets(1).Activate
For i = 1 To 999
If Range("A" & i).Value = "" Then Exit For
colA(i - 1) = Range("A" & i).Value
colB(i - 1) = Range("B" & i).Value
cnt = cnt + 1
Next
ReDim Preserve colA(cnt)
ReDim Preserve colB(cnt)
End With
For each oldname in colA()
'Stuck here...
Next
End Sub
我意识到我可以再次遍历 targetWb,并且对于每个选项卡名,在 ColA() 中找到该选项卡名的位置,并使用来自 tabB() 的相同位置名重命名它 - 但我想知道是否有更快/更好的方法来做到这一点。
解决方案
您可以像这样遍历活动工作簿:
Sub t()
Dim mainWB As Workbook, tempWB As Workbook
Dim wb As Workbook
Set mainWB = ActiveWorkbook
For Each wb In Application.Workbooks
'Loops through the workbooks.
Debug.Print wb.Name
If wb.Name Like "Book*" Then
Set tempWB = wb
End If
Next wb
End Sub
编辑:由于您只有两个打开的工作簿,您可以缩短它:
Sub t()
Dim mainWB As Workbook, tempWB As Workbook
Dim wb As Workbook
Set mainWB = ActiveWorkbook ' MAKE SURE THIS IS CORRECT!! May need `ThisWorkbook` if the new temporary one becomes the active one.
For Each wb In Application.Workbooks
'Loops through the workbooks.
Debug.Print wb.Name
If wb.Name <> mainWB.Name And wb.Name <> "PERSONAL.XLSB" Then
Set tempWB = wb
' Now do whatever you need with the Temporary workbook.
End If
Next wb
End Sub
推荐阅读
- eclipse - 无法安装 Eclipse Antlr4 Ide - 更新站点已过期
- javascript - 正则表达式匹配两个元素或不匹配
- http - CAS注销并拦截POST请求
- scom - 为 Azure 日志分析配置现有 SCOM 代理
- typescript - Typescript:axios 获取、文件写入和文件读取的异步问题
- big-o - 大 O 表示法:负对数参数
- python - 任务处于“运行”状态,这不是执行的有效状态。必须清除任务才能运行
- android - Microsoft Graph v3.0.0 导致重复类 javax.activation ... 编译时
- java - 在 ListView 中显示 Firebase 数据
- javascript - 由 JavaScript 在 R 数据表中创建的闪亮输入仅响应一次