我对VBA不太满意,但我正在努力完成以下任务:
如何根据前一周复制工作表并确定名称?如何在同一个宏中清除这个新工作表的某些单元格?
到目前为止我只有:
Sub New_Week()
Worksheets(ActiveSheet.Name).Copy After:=Worksheets(ActiveSheet.Name)
End Sub
答案 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