基本上我的目标是:
我的代码
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
我遇到的问题是在哪里添加我的第二个范围以及如何根据它更改一个单元格。
答案 0 :(得分:0)
将“模板”工作表复制到信息工作表后的位置时,您立即知道其Worksheet.Index property将大于信息的.Index
工作表。在With ... End With statement中使用此标识来标识新工作表并在那里执行所有操作。
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
之前使用工作表.Name property。
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 property将更改为新工作表。如果要从Info工作表(原始ActiveSheet)中检索信息,则需要在复制过程开始之前使用工作表对象引用Set
。由于循环在For ... Next
开始时在信息工作表上建立了单元格范围,因此您仍然可以使用rcell
作为信息工作表上的参考点。