当前位置: 代码迷 >> VBA >> excel 2010 Workbook_BeforeSave饮弹出另存为窗口后保存不了
  详细解决方案

excel 2010 Workbook_BeforeSave饮弹出另存为窗口后保存不了

热度:5468   发布时间:2013-02-26 00:00:00.0
excel 2010 Workbook_BeforeSave中弹出另存为窗口后保存不了
我在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
  相关解决方案