【问题标题】:Excel VBA prevent SaveAs .xlsxExcel VBA 阻止 SaveAs .xlsx
【发布时间】:2015-04-27 06:46:21
【问题描述】:

我制作了一套带有宏的记分卡计算器。我将工作簿分发为 .xls 文件。但是,有时用户会将工作簿另存为 .xlsx 文件,从而删除所有 VBA 代码和宏。内置函数显然不再起作用了。

有什么方法可以让标准 Excel SaveAs 函数排除 .xlsx 作为选项?

【问题讨论】:

  • 对不起...标题应该是 VBA 而不是 VBD....
  • 这很难实现。我和我的同事也有同样的问题。您基本上可以创建一个特定的按钮来执行宏保存。

标签: excel vba


【解决方案1】:

您可以自己替换标准的 FileSave 对话框。不幸的是,您无法操纵过滤器列表来删除除“.xlsm”和“.xls”之外的任何内容,但您可以捕获选定的文件名并采取相应措施...

建议:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim FD As FileDialog, FTyp As Long

    MsgBox "Sub Workbook_BeforeSave"

    ' this Sub will never save, we save through the Dialog box below
    Cancel = True

    ' reference a SaveAs Dialog
    Set FD = Application.FileDialog(msoFileDialogSaveAs)
    FD.Show

    If FD.SelectedItems.Count = 0 Then
        MsgBox "Nothing chosen"
        Exit Sub
    Else
        ' check for proper extension
        If Right(FD.SelectedItems(1), 3) = "xls" Or Right(FD.SelectedItems(1), 4) = "xlsm" Then
            MsgBox "saving as " & FD.SelectedItems(1)

            If Right(FD.SelectedItems(1), 3) = "xls" Then
                ' different enum before Excel 2007
                If Val(Application.Version) < 12 Then
                    FTyp = -4143           ' xls pre-2007
                Else
                    FTyp = 56              ' xls post-2007
                End If
            Else
                FTyp = 52                  ' xlsm post-2007
            End If

            ' we don't want to come here again, so temporarily switch off event handling
            Application.EnableEvents = False
            Me.SaveAs FD.SelectedItems(1), FTyp
            Application.EnableEvents = True

        Else
            MsgBox "selected wrong file format ... not saving"
        End If
    End If

End Sub

【讨论】:

  • 谢谢 MikeD。我们最终用与您所展示的非常相似的东西解决了这个问题。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多