vba 如何保存递增数字的excel文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26365194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:50:22  来源:igfitidea点击:

How to save excel file with incrementing number?

excelvbaincrement

提问by Circuitsandcoffee

I am looking for VBA to add to my macro that will increment the file name if the file name already exists.

我正在寻找 VBA 添加到我的宏中,如果文件名已经存在,它将增加文件名。

Current Code:

当前代码:

Dim filepath As String
Dim filename As String
Dim filepatharch As String
Dim filedate As String
Dim filelist As String

'Grab FROM list number
Sheets("TD File").Select
Range("G4").Select
filelist = ActiveCell.Value


'Grab today's date
filedate = Format(Now, "MMDD01.") --------------Currently where the '01' comes from (see below)

'Set where to save and the file naming convention
filepath = "\home\serverfolder\FileDrop\"
tdfilename = "TD" & filedate & filelist
'& ".txt"


'Set where to save and the file naming convention
filepatharch = "\home\myfolder\archive"
tdfilename = "TD" & filedate & filelist
'& ".txt"


'Save THXXXXXX.XXX & TDXXXXXX.XXX as flat files
   'Workbooks("MYWORK01").Activate
    Sheets("TDflatfile").Copy
    ActiveWorkbook.SaveAs filename:= _
        "\home\serverfolder\FileDrop\" & tdfilename, FileFormat:=xlCSV, _
        CreateBackup:=False
    ActiveWindow.Close

An example of the saved file name would be "TD101401.600". TD + MMDD + 01 + .XXX. I would like the "+ 01 " to be the number that increments, that way I could have a file that is "TD101402.600" and so forth. Currently if the file exists for the same .XXX number and date combo, it gets overwritten. The .XXX cannot be the increment.

保存的文件名的示例是“TD101401.600”。TD + MMDD + 01 + .XXX。我希望“+ 01”是递增的数字,这样我就可以拥有一个“TD101402.600”等文件。目前,如果文件存在相同的 .XXX 编号和日期组合,则会被覆盖。.XXX 不能是增量。

Is this possible?

这可能吗?

采纳答案by Circuitsandcoffee

Someone suggested this and it worked for me:

有人建议这样做,它对我有用:

Dim filecount As Integer

Do While Len(Dir(filepatharch & thfilename)) <> 0
        filecount = filecount + 1
        filedate = Format(Now, "MMDD0" & filecount & ".")
        tdfilename = "TD" & filedate & filelist
        thfilename = "TH" & filedate & filelist
Loop

回答by RomeuForte

Just put a conditional loop with Dir()

只需放置一个条件循环 Dir()

Do While ((Dir(filepath & tdfilename)) <> Empty)
inc = inc+1
filedate = Format(Now, "MMDD") & "." & Format(inc, "00")
tdfilename = "TD" & filedate & filelist
Loop