vba - 使用VBA通过浏览将文件保存在所需文件夹中

标签 vba excel

编写代码以将具有定义文件名的文件保存到用户输入的特定文件夹中。但是,文件保存在指定位置之前的位置。例如,我提供的文件保存路径为“C:\Users\arorapr\Documents\PAT”,但文件将其保存在路径“C:\Users\arorapr\Documents”中。我写了下面的代码。

 File_Name = Format(Now(), "DDMMYYYY") & "_" & LName & EmpIN & "_" & Range("C6").Value & "_" & Range("J3").Value & "_" & "PAT"
 Application.DisplayAlerts = False
 MsgBox "Please select the folder to save PAT"

 With Application.FileDialog(msoFileDialogFolderPicker)
 .AllowMultiSelect = False
    .Show
End With

 ActiveWorkbook.saveas Filename:=File_Name & ".xlsm", FileFormat:=52
 Application.DisplayAlerts = True

 ActiveWorkbook.Close

最佳答案

您面临的挑战是您正在打开一个文件对话框,但没有使用用户在saveas中的选择。尝试按照以下思路进行操作:

Sub SaveFile()

    Dim FolderName As String

    File_Name = Format(Now(), "DDMMYYYY") & "_" & LName & EmpIN & "_" & Range("C6").Value & "_" & Range("J3").Value & "_" & "PAT"
    Application.DisplayAlerts = False
    MsgBox "Please select the folder to save PAT"

    ' Pop up the folder-selection box to get the folder form the user:
    FolderName = GetFolder()

    ' If the user didn't select anything, you can't save, so tell them so:
    If FolderName = "" Then
        MsgBox "No folder was selected. Program will terminate."
        Exit Sub
    End If

    ' Create a path by combining the file and folder names:
    File_Name = FolderName & "\" & File_Name & ".xlsm"

    ActiveWorkbook.SaveAs Filename:=File_Name, FileFormat:=52
    Application.DisplayAlerts = True

    ActiveWorkbook.Close
End Sub


' A separate function to get the folder name and return it as a string
Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With

NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

希望有帮助。

关于vba - 使用VBA通过浏览将文件保存在所需文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50509569/

相关文章:

vba - 如何创建dBase(IV?)文件?

excel - Countif 动态标准范围

vba - 查找已填充任何颜色的所有单元格并突出显示 Excel VBA 中相应的列标题

regex - Excel VBA 使用正则表达式查找和屏蔽 PAN 数据以实现 PCI DSS 合规性

excel - 捕获用户错误并在错误后重新启用 application.events

具有日期条件的表的 vba excel AdvancedFilter 方法不起作用

c# - 如何通过 C# WPF 隐藏 Excel 工作表中的网格线

java - Java 中的批量输入?

excel - 将数据透视缓存从一个文件上的数据透视传输到另一个文件上的数据透视?

excel - 使用 VBA 检测 Excel 版本中是否启用了动态数组