复制工作表,根据范围重命名工作表,并根据范围编辑复制的工作表

时间:2015-10-29 17:13:31

标签: excel vba excel-vba copy

基本上我的目标是:

  1. 根据模板创建副本,并根据名称列表重命名(我已经找到了这部分)
  2. 根据另一个单元格范围更改副本中的两个单元格
  3. 我的代码

     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
    

    我遇到的问题是在哪里添加我的第二个范围以及如何根据它更改一个单元格。

1 个答案:

答案 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作为信息工作表上的参考点。