我在excel 2010中写了如下的代码,为了点击save后弹出save as对话框,并且命名文件.
但是发现点了弹出框的save后并没有保存,为什么?
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim Name As String
With ThisWorkbook
Name = Worksheets("Sheet1").Range("B7").Value
Dim dlgSaveAs As FileDialog
'Set the dialog type
Set dlgSaveAs = Application.FileDialog(msoFileDialogSaveAs)
With dlgSaveAs
.InitialFileName = Name
.FilterIndex = 2
'Display the dialog
.Show
End With
End With
End Sub
如果我再.Show后面增加.Execute的话,执行会报错
------解决方案--------------------------------------------------------
Dim Name As String
With ThisWorkbook
Name = Worksheets("Sheet1").Range("B7").Value
Dim dlgSaveAs As FileDialog
'Set the dialog type
Set dlgSaveAs = Application.FileDialog(msoFileDialogSaveAs)
With dlgSaveAs
.InitialFileName = Name
.FilterIndex = 2
'Display the dialog
.Show
End With
End With
是因为没有Execute而没有保存
添加Execute后 可以保存
但是有个问题 执行Execute时文件也进行了保存动作
还会触发Workbook_BeforeSave这个函数
所以文件出错想不出错的话
把代码移动到普通的函数中
Sub b()
Dim Name As String
With ThisWorkbook
Name = Worksheets("Sheet1").Range("B7").Value
Dim dlgSaveAs As FileDialog
'Set the dialog type
Set dlgSaveAs = Application.FileDialog(msoFileDialogSaveAs)
With dlgSaveAs
.InitialFileName = Name
.FilterIndex = 2