首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VBA >

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

2013-02-17 
excel 2010 Workbook_BeforeSave中弹出另存为窗口后保存不了我在excel 2010中写了如下的代码,为了点击save

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


            'Display the dialog
            .Show
            .Execute
            
        End With
    End With
End Sub

热点排行