克隆表,命名,清除单元格 - Excel VBA

时间:2017-10-30 10:58:02

标签: excel vba excel-vba

我对VBA不太满意,但我正在努力完成以下任务:

  • 我有一张带有特定信息的表格(第50周)。
  • 我想要一个创建新工作表(第51周)的按钮(宏) 同一张表,只清除内容(某个 小区范围)。
  • 表格中的第一列应基于前一周的公式。如何才能使其适应每个新的一周工作?

如何根据前一周复制工作表并确定名称?如何在同一个宏中清除这个新工作表的某些单元格?

到目前为止我只有:

Sub New_Week()
    Worksheets(ActiveSheet.Name).Copy After:=Worksheets(ActiveSheet.Name)
End Sub

1 个答案:

答案 0 :(得分:0)

此代码并未考虑更改年份,因此如果您在工作簿中已经运行了52周,那么它将很乐意创建第53,54周等等。

您不需要选择当前周,代码会根据名为Week xx的工作表搜索最高周数。
它清除范围D2:G2和H5:K8。 工作表上'Week xx'!的任何引用都会更新到上一周,方法与按键盘上的Ctrl+H相同。

Sub CreateNewSheet()

    Dim wrkSht As Worksheet
    Dim lWkNum As Long
    Dim lCurNum As Long
    Dim sht_LastWeek As Worksheet
    Dim sht_NewWeek As Worksheet

    'Find previous week and set reference to it.
    For Each wrkSht In ThisWorkbook.Worksheets
        If IsNumeric(Replace(wrkSht.Name, "Week ", "")) Then
            lCurNum = CLng(Replace(wrkSht.Name, "Week ", ""))
            If lCurNum > lWkNum Then lWkNum = lCurNum
        End If
    Next wrkSht
    Set sht_LastWeek = ThisWorkbook.Worksheets("Week " & lWkNum)

    'Create new sheet, set reference to it and rename.
    sht_LastWeek.Copy After:=Sheets(sht_LastWeek.Index)
    Set sht_NewWeek = Sheets(sht_LastWeek.Index + 1)
    sht_NewWeek.Name = "Week " & lCurNum + 1

    'Clear the cells and relink formula to previous sheet.
    With sht_NewWeek
        .Range("D2:G2,H5:K8").ClearContents
        .Cells.Replace What:="'Week " & lCurNum - 1 & "'!", _
                       Replacement:="'Week " & lCurNum & "'!", _
                       LookAt:=xlPart
    End With

End Sub