VBA:每天从文件末尾删除格式化日期并重新保存

时间:2018-09-12 16:11:25

标签: excel vba

每天我都会收到一个自动文件,格式为DailyFile 09-12-18.xlsx。

我已经编写了一个VBA模块,以查找名为(在这种情况下)DailyFile的文件,并使用新的每日数据更新必要的电子表格。

但是,我需要一种从日常文件中删除日期部分的方式,以便我的模块可以识别它,但是我还需要为我保留每个日常文件的副本(文件名中带有日期)。记录。

换句话说,我的主电子表格需要从每日文件中提取最新数据(可以从昨天开始覆盖),但我也想保存原始数据的副本。

这是我到目前为止所拥有的...它不起作用:

Option Explicit


Sub changefilename()

Dim tdate As Variant
Dim ofile As Workbook
Dim TestFile As String



tdate = Date
tdate.NumberFormat = "mm-dd-yy"

Set ofile = Workbooks.Open("C:\Users\Research\Documents\Daily File " & tdate & ".xlsx")
ofile.SaveAs Filename:=TestFile


End Sub

3 个答案:

答案 0 :(得分:3)

 Option Explicit 

    Sub changefilename()

 Dim ofile As Workbook
 Dim TestFile As String 


    '##What we want the new save file to be called, with path:
TestFile = "C:\Users\Research\Documents\TEST.xlsx"


    '##Searches for a file that concats the file name with today's date.
    '##Use format(Date,____) for how your date is formatted. No need to assign a variable to the Date.
Set ofile = Workbooks.Open("C:\Users\Research\Documents\DailyFile" & Format(Date, "mm-dd-yy") & ".xlsx")

       '##Saves the old file in the desired path!
ofile.SaveAs Filename:=TestFile


    End Sub

答案 1 :(得分:2)

.NumberFormat是单元格属性。 tdate不是单元格,而是Variant,因此不具有该属性。

使用Format函数对其进行格式化:

Option Explicit

Sub changefilename()

    Dim tdate As Variant
    Dim ofile As Workbook
    Dim TestFile As String

    tdate = Format(Date, "mm-dd-yy")

    Set ofile = Workbooks.Open("C:\Users\Research\Documents\Daily File " & tdate & ".xlsx")
    ofile.SaveAs Filename:=TestFile

End Sub

答案 2 :(得分:1)

Sub changefilename()

    Dim tdate As String
    Dim ofile As Workbook
    Dim ofile_Name As String

    tdate = Format(Date, "MM-DD-YY")

    Set ofile = Workbooks.Open("C:\Users\Research\Documents\Daily File " & tdate & ".xlsx")

    'change the character 9 to whatever the length of the file name
    ofile_Name = Left(ofile.Name, 9)

    ofile.SaveAs Filename:=ofile_Name   

End Sub