【问题标题】:Excel Macro - Automate FilenameExcel 宏 - 自动文件名
【发布时间】:2021-12-23 13:28:48
【问题描述】:

解决了,谢谢

我有为我们的数据创建导出文件的宏。我们每天都会产生很多文件,所以我正在尝试微调一些东西。

在宏结束时,我想将文件另存为 .xlsx,文件名使用增量批号和今天的日期。

文件夹中的示例文件名:

B001 客户名导出 051121

B002 客户名导出 091121

B003 客户名导出 101121

有没有办法自动增加数字?使用 +1 表示最高值。

下一个文件将保存为 B004 ClientName Export

我已经设法填充了一个消息框,它显示了当前的最高数字,我的困难是使用它来保存具有下一个数字的文档

Option Explicit

Public Sub Example()
Const FolderPath = "Z:"
Const FileExt = "xlsx"
Debug.Print GetNextFileNum(FolderPath, FileExt)
End Sub

Public Function GetNextFileNum(ByVal TargetFolder As String, ByVal Extension As String) As Integer
Dim Folder As Object, File As Object

With CreateObject("Scripting.FileSystemObject")
    Set Folder = .GetFolder(TargetFolder)
    For Each File In Folder.Files
        If IsNumeric(Mid(File.Name, 2, 3)) And FileExt(File.Name) = Extension Then
            GetNextFileNum = IIf(CInt(Mid(File.Name, 2, 3)) > GetNextFileNum, CInt(Mid(File.Name, 2, 3)), GetNextFileNum)
        End If
    Next File
End With

GetNextFileNum = GetNextFileNum + 1

  ActiveWorkbook.SaveAs Filename:= _
    "Z:" & "F00" & GetNextFileNum & " 
One " & _
    Format(Date, "ddmmyy") & ".xlsx" _
    , FileFormat:=xlOpenXMLStrictWorkbook, CreateBackup:=False

End Function

Public Function FileExt(ByVal Path As String) As String
With CreateObject("Scripting.FileSystemObject"): FileExt = .GetExtensionName(Path): End With
End Function

【问题讨论】:

  • 您具体遇到了什么困难?

标签: excel vba filenames auto-increment


【解决方案1】:

托比。

你可以试试这样的。

Sub LoopThroughFiles()
 
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
 
Set oFSO = CreateObject("Scripting.FileSystemObject")
AcFolder = ActiveWorkbook.Path
 
Set oFolder = oFSO.GetFolder(AcFolder)
 
Bigger = 0
 
For Each oFile In oFolder.Files
    If Left(oFile.Name, 1) = "B" Then
       If CInt(Mid(oFile.Name, 2, 3)) > Bigger Then
          Bigger = CInt(Mid(oFile.Name, 2, 3))
       End If
    End If
Next oFile
    
    NextNumber = Bigger + 1
    MsgBox NextNumber
     
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2011-02-11
    相关资源
    最近更新 更多