复制工作表,基于范围重新命名工作表,并根据范围编辑复印的工作表
本质上我的目标是:
- 根据模板创build副本,并根据名称列表对其进行重命名(我已经理解了这一部分)
- 根据另一个单元格区域更改副本中的两个单元格
我的代码
Sub CopyInfoSheetandInsert() Dim rcell As Range Dim hcell As Range Dim Info As Worksheet Set Info = ActiveSheet For Each rcell In Range("B2:B30") If rcell.Value <> "" Then Sheets("Team Member (2)").Copy After:=Sheets("Info") Sheets("Team Member (3)").Name = rcell.Value End If Next rcell End Sub
我遇到麻烦的是在哪里添加我的第二个范围,以及如何更改基于它的单元格。
当您将“模板”工作表复制到“信息”工作表之后的位置时,立即知道其Worksheet.Index属性将比Info工作表的.Index
。 在With … End With语句中使用此标识来标识新工作表并在其中执行所有操作。
Sub CopyInfoSheetandInsert() Dim rcell As Range, hcell As Range, Info As Worksheet Set Info = ActiveSheet For Each rcell In Info.Range("B2:B30") If rcell.Value <> "" Then Sheets("Team Member (2)").Copy After:=Sheets("Info") With Sheets(Sheets("Info").Index + 1) .Name = rcell.Value .Range("A1") = "this is the new worksheet" '<~~perform the other operations like this .Range("A2") = Info.Range("Z99").Value '<~~cannot reference Info as ActiveSheet anymore. Need direct worksheet reference like this. .Range("A3") = rcell.Offset(0, 1).Value '<~~you can still use rcell as a reference point for other information End With End If Next rcell End Sub
或者,一旦新的工作表被命名,您可以在循环到新的rcell
之前使用Worksheet .Name属性 。
Set Info = ActiveSheet For Each rcell In Info.Range("B2:B30") If rcell.Value <> "" Then Sheets("Team Member (2)").Copy After:=Sheets("Info") Sheets("Team Member (3)").Name = rcell.Value With Sheets(rcell.Value) .Range("A1") = "this is the new worksheet" '<~~perform the other operations like this .Range("A2") = Info.Range("Z99").Value '<~~cannot reference Info as ActiveSheet anymore. Need direct worksheet reference like this. .Range("A3") = rcell.Offset(0, 1).Value '<~~you can still use rcell as a reference point for other information End With End If Next rcell
请记住当您复制时,当前的ActiveSheet属性将更改为新的工作表。 如果您要从“信息”工作表(原始ActiveSheet)检索信息,则需要在复制过程开始之前使用您Set
的工作表对象引用。 由于在For ... Next
开始时,循环在Info工作表上build立了单元格范围,所以仍然可以在Info工作表上使用rcell
作为参考点。