显示excel保存为对话框并预填充单元格引用

时间:2018-02-02 02:38:19

标签: excel vba excel-vba

没有编码知识,我试图使用这里找到的一些代码:Automatically name a file based on cell data when saving a spreadsheet?。感谢Jean-François Corbett

我已按如下方式调整以显示对话框:

Sub SaveAsString()

Dim strPath As String
Dim strFolderPath As String

strFolderPath = "N:\PROJECTS\"

    strPath = strFolderPath & _
        Sheet1.Range("B2").Value & "_" & _
        Sheet1.Range("B6").Value & "_" & _
        Sheet1.Range("X1").Value & "-JS-1" & ".xlsm"

Application.Dialogs(xlDialogSaveAs).Show strPath
ActiveWorkbook.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled

End Sub

我正在打开一个.xltm文件,并尝试保存,可以选择显示单元格引用组合的N:\PROJECTS\子文件夹。

对话框显示正常,已显示N:\PROJECTS。但是,它不会填充文件名,除非该文件首先保存为.xlsm。然后它总是试图覆盖。

2 个答案:

答案 0 :(得分:0)

这对我有用,使用的代码技术略有不同。

Option Explicit

Sub SaveAsString()

    Dim strPath As String
    Dim strFolderPath As String

    ChDir "N:\PROJECTS\" 'set directory with this line

    With Sheet1

        strPath = .Range("B2").Value
        strPath = strPath & "_" & .Range("B6").Value
        strPath = strPath & "_" & .Range("X1").Value 
        strPath = strPath & "-JS-1.xlsm"

    End With

    Application.Dialogs(xlDialogSaveAs).Show strPath 'load file name with this argument
    ActiveWorkbook.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled

End Sub

答案 1 :(得分:0)

剩下的主要问题是从模板打开并不会自动保存为.xlsm。显然,Application.Dialogs不支持文件过滤器,因此使用GetSaveasFileName可以更好地解决问题。

完整代码如下:

Sub SaveAsString()

Dim strPath As String
Dim strFolderPath As String

strFolderPath = "N:\PROJECTS\"

     strPath = strFolderPath & _
        Sheet1.Range("B2").Value & "_" & _
        Sheet1.Range("B6").Value & "_" & _
        Sheet1.Range("X1").Value & "-JS-1" & ".xlsm"

fileSaveName = Application.GetSaveAsFilename(strPath _
 , fileFilter:="Excel Files (*.xlsm), *.xlsm")

End Sub