打开另存为窗口并从单元格

时间:2017-03-17 19:40:36

标签: excel excel-vba vba

我试图打开另存为窗口并从单元格填充文件名和文件路径

这里是我的代码,它填充文件名并在文件路径中打开另存为窗口但是当我单击保存时,文件永远不会出现在它想要保存的位置。

Sub Save()

'Adds formula to show file path
ActiveSheet.Range("I26") = "=LEFT(CELL(""filename"",RC),FIND(""["",CELL(""filename"",RC),1)-1)"

'Adds formula to show file name
ActiveSheet.Range("J26") = "=MID(CELL(""filename""),FIND(""["",CELL(""filename""))+1,(FIND(""]"",CELL(""filename""))-FIND(""["",CELL(""Filename""))-8))"

ActiveSheet.Calculate 'Calculate sheet

'this will remove the formula from the cell making it text only
ActiveSheet.Range("I26") = ActiveSheet.Range("I26")
ActiveSheet.Range("J26") = ActiveSheet.Range("J26")


Dim FilePath As String
Dim FileName As String
FilePath = ActiveSheet.Range("I26").Value
FileName = ActiveSheet.Range("J26").Value


Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)

With fPth
    .InitialFileName = FilePath & FileName & ".xlsm"
    .Title = "Save your File"
    .InitialView = msoFileDialogViewList
    .Show
End With


End Sub

1 个答案:

答案 0 :(得分:1)

文件对话框实际上并不保存文件 - 它只是提示用户输入文件名或允许用户更改默认文件名。您必须返回所选的文件名并将其保存为以下内容:

Dim fPth As Object
Set fPth = Application.FileDialog(msoFileDialogSaveAs)

With fPth
  .InitialFileName = FileName & ".xlsm"
  .Title = "Save your File"
  .InitialView = msoFileDialogViewList
  If .Show <> 0 Then
    ThisWorkbook.SaveAs FileName:=.SelectedItems(1), FileFormat:=xlWorkbookNormal
  End If
End With