我想在VBA中减去一小时

我在下面添加了我的代码片段。 我正在导入每2小时生成一个文件。 由于时间的开始,我需要减去一小时,并将其添加到文件名导入文件。 例如:

文件名“mm”(月) “dd”(日) “hh”(小时).txt

小时需要包括前导0。

Dim hour As String Dim day As String Dim month As String Dim project As String Set ws = Worksheets("Master") Set ws1 = Worksheets("MQL_RAW") Set ws2 = Worksheets("BOM") file_name = Sheets("Master").Range("F" & rep1).Value file_name2 = Sheets("Master").Range("G" & rep1).Value output_sheet = Sheets("Master").Range("L" & rep1).Value row_number = Sheets("Master").Range("M" & rep1).Value hour = Format(Time, "Hh") - Time(1, 0, 0) day = Format(Date, "Dd") month = Format(Date, "Mm") project = Sheets("Master").Range("B2").Value LastRow = Cells(ws1.Rows.Count, 10).End(xlUp).Row ws1.Activate Columns("A:A").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select Range(Selection, Selection.End(xlDown)).Select Selection.Delete Shift:=xlToLeft ws.Activate aa = file_name2 & Format(Date, "yyyymmdd") & "_" & Format(Time, "Hh") With Sheets(output_sheet).QueryTables.Add(Connection:="TEXT;" + file_name + "\" + month + "\" + day + "\" + file_name2 & Format(Date, "yyyymmdd") & "_" & hour & ".txt", Destination:=Sheets(output_sheet).Range("$A$" + row_number)) '.Name = file_name & Format(Date, "yyyymmdd") & "_" & Format(Time, "Hh") .FieldNames = True .RowNumbers = False 

使用这样的东西:

 filename = "name_" & Format(Now - TimeSerial(1, 0, 0), "MMDDHH") & ".txt" 

另外,使用像这样的东西:

 Dim reportStart As Date reportStart = Now 

在你的代码的开始,然后当保存在最后,只需使用:

 filename = "name_" & Format(reportStart, "MMDDHH") & ".txt"