我想在VBA内减去一小时

时间:2016-05-16 09:57:42

标签: excel vba excel-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

1 个答案:

答案 0 :(得分:1)

使用类似的东西:

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

或者,使用类似的东西:

Dim reportStart As Date
reportStart = Now

在代码开头,然后在最后保存时,只需使用:

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