SaveAs or save dialog box for DOM in VBA

时间:2017-08-04 12:28:27

标签: excel-vba vba excel

I'm trying to save a DOM doc and the save method works just fine:

xDoc.Save "myFileName"

but I'd like the user to be able to pick the path and potentially the name. So I tried:

xDoc = "Application.FileDialog(msoFileDialogSaveAs).Show"
If myNum <> 0 Then
    XDoc = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
End If

This opened a SaveAs dialog box but when I click ok I get a run time "object doesn't support this property or method". I knew it probably wouldn't work but thought it made sense that it should.

Anyone know how to open a SaveAs dialog box with VBA to save a DOM(Document)?

2 个答案:

答案 0 :(得分:1)

所以这是一个问题,因为您使用的是文字字符串,而不是调用方法:

xDoc = "Application.FileDialog(msoFileDialogSaveAs).Show"
'The value of xDoc has been assigned literally as above!!!

相反,请执行此操作以实例化FileDialog对象,并使用它。 Show它,请确保已使用它(如果用户取消Show将返回False,然后.Execute执行SaveAs操作

Dim fdlg As FileDialog
Set fdlg = Application.FileDialog(msoFileDialogSaveAs)
fdlg.Title = "Save XML file as..."
fdlg.FilterIndex = 5  'Defaults to the XML Data file filter
If fdlg.Show() Then
    xDoc.Save fdlg.SelectedItems(1)         
Else: 
    MsgBox "File has not been saved!"
End If

注意:上述代码中没有包含错误处理,如果文件已经存在,则会导致失败或发出警告/等等。根据需要进行修改。

答案 1 :(得分:0)

虽然它可能不是最好的方法,但我找到了有效的方法。如果有人有更好的,请发帖!

XDoc.Save (Application.GetSaveAsFileName(InitialFileName:="NewFile", FileFilter:="XML Data, *.xml", Title:="Save XML as"))