我正在尝试使用vba来替换上周的日期,以更新数字。我已经尝试了以下但我不认为我理解替换功能在VBA中是如何工作的。
Dim lastweek As String
lastweek = Format(Now - 7, "yyyymmdd")
Dim thisweek As String
thisweek = Format(Now, "yyyymmdd")
Replace (lastweek,lastweek,thisweek)
另外,我上周使用正确的公式,我想在7天前提取日期吗?
答案 0 :(得分:2)
将上周转换为日期并为其添加7天,以获得下周值
Function MyWeek(lastweek As String) As String
lw = DateSerial(CInt(Left(lastweek, 4)), CInt(Mid(lastweek, 5, 2)), CInt(Right(lastweek, 2)))
MyWeek = Format(lw + 7, "yyyymmdd")
End Function
然后使用,
=REPLACE(A1,SEARCH("2*]",A1,1),8,Myweek(MID(A1,SEARCH("2*]",A1,1),8)))
将日期替换为新日期,假设您要替换的字符串位于单元格A1
答案 1 :(得分:1)
您还可以在VBA中使用自动过滤器选项。只需将以下代码粘贴到模块中,如下所示:
Sub date_change()
Dim filter_column As Range
Dim start_date As Date
Dim end_date As Date
With ActiveSheet
.AutoFilterMode = False
Set filter_column = .Range("j1") 'give the column which has the date that needs to be changed
end_date = Now - Weekday(Now, vbSunday)
end_date = DateSerial(Year(end_date), Month(end_date), Day(end_date))
start_date = end_date - 6
start_date = DateSerial(Year(start_date), Month(start_date), Day(start_date))
.Rows(1).AutoFilter Field:=filter_column.Column, Criteria1:=">=" & start_date, Operator:=xlAnd, Criteria2:="<=" & end_date
.Range(.Cells(2, filter_column.Column), .Cells(.Rows.Count, filter_column.Column).End(xlUp)).Select
If WorksheetFunction.Subtotal(3, Selection) <> 1 Then
Selection.ClearContents
Selection = Now
End If
End With
End Sub