使用VBA替换列中所有单元格的工作表名称

时间:2017-06-16 19:13:30

标签: excel vba excel-vba

我有一个列(AF),其中公式当前设置为:

=IFERROR(INDEX('2017_03 Cash'!D:D,MATCH(G:G,'2017_03 Cash'!A:A,0)),0)

我希望'2017_03 Cash'部分根据特定标签的名称进行更改。例如,这是3月(03),然后是下个月我创建一个新工作表,并被称为"2017_04 Cash" ...等。

如果你看下面的代码,你会看到

Set CashWS = Sheets.Add
CashWS.Name = "2017_0" & MonthVal & " Cash"

我想在脚本中包含一些内容,它会将AF列中公式的'2017_03 Cash'部分更改为CashWS.Name = "2017_0" & MonthVal & " Cash"

因此,所有3个应该基本上由4&替换。然后将公式一直向下拖动到AF列的最后一行。

Sub AddSheets()

Dim PrevSheet As String
Dim CashWS As Worksheet
Dim MonthVal As String
Dim lr As Long

NewSheet = InputBox("Which month is this Commissions statement for?")
PrevSheet = InputBox("What was the previous month?")

Worksheets(PrevSheet).Copy After:=Worksheets("Summary")
ActiveSheet.Name = NewSheet

With Worksheets(NewSheet)
lr = .Cells(.Rows.Count, "AG").End(xlUp).Row
    .Range(.Cells(5, "AE"), .Cells(lr, "AE")) = .Range(.Cells(5, "AG"), .Cells(lr, "AG")).Value
End With    

Range("D2").Select
ActiveCell.FormulaR1C1 = "=EOMONTH(DATE(2017,MONTH(DATEVALUE(MID(CELL(""filename"", RC[-5]), FIND(""]"", CELL(""filename"", RC[-5])) + 1, 255)&""1"")+1),1),0)"
Selection.NumberFormat = "m/d/yyyy"

Range("D3").Select
ActiveCell.FormulaR1C1 = "=MONTH(R[-1]C)"
Range("D3").Select
Selection.NumberFormat = "General"
MonthVal = ActiveCell.Value


Set CashWS = Sheets.Add
CashWS.Name = "2017_0" & MonthVal & " Cash"

End Sub

1 个答案:

答案 0 :(得分:0)

有多种方法可以创建依赖于日期的字符串。我倾向于使用带有掩码的Format,否则该掩码将被解释为数字。

Dim oldws As String, newws As String, oldmn As Long, newmn As Long

oldmn = 3
newmn = Month(Date)
oldws = Format(oldmn, "\2\0\1\7\_00 \C\a\s\h")    '2017_03 Cash
newws = Format(Date, "yyyy_mm \C\a\s\h")          '2017_06 Cash (today is 16-Jun-2017)

With Worksheets("sheet1")
    With .Columns("AF")
        .Replace What:=oldws, Replacement:=newws, LookAt:=xlPart, _
                 SearchOrder:=xlByRows, MatchCase:=False, _
                 SearchFormat:=False, ReplaceFormat:=False
    End With
End With