2

我正在研究 Excel 的 _Workbook.SaveAs API

如果有同名文件,我需要总是替换。不应该有对话框询问我是否要覆盖文件。

现在,代码是:

app->put_DisplayAlerts(LOCALE_USER_DEFAULT, VARIANT_FALSE);
activeWorkbook->SaveAs(filePath,
                        fileType,
                        vtMissing,
                        vtMissing,
                        vtMissing,
                        vtMissing, 
                        Excel::xlNoChange);
app->put_DisplayAlerts(LOCALE_USER_DEFAULT, VARIANT_TRUE);

问题是这会禁用所有警报。我仍然想要其他警报。

例如,当用户尝试将带有宏的工作簿保存为“.xlsx”格式时,应该有一个警告对话框告诉用户不会包含宏。

问题

有没有办法为所有版本的 Excel 实现这一目标?

提前感谢=]

4

1 回答 1

1

在 Excel VBA 中,您可以简单地执行以下操作:

Excel.Application.DisplayAlerts = False

这是我在现有文件上保存文件时通常使用的代码。我现在还想检查我试图覆盖的文件是否已打开以供其他用户通过以下功能(我从 SO 获得)进行编辑:

        Enum IsFileOpenStatus
                    ExistsAndClosedOrReadOnly = 0
                    ExistsAndOpenSoBlocked = 1
                    NotExists = 2
        End Enum


        Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus

        'ExistsAndClosedOrReadOnly = 0
        'ExistsAndOpenSoBlocked = 1
        'NotExists = 2

        With New FileSystemObject
                    If Not .FileExists(FileName) Then
                                IsFileReadOnlyOpen = 2  '  NotExists = 2
                                Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
                    End If
        End With

        Dim iFilenum As Long
        Dim iErr As Long
                    On Error Resume Next
                                iFilenum = FreeFile()
                                Open FileName For Input Lock Read As #iFilenum
                                Close iFilenum
                                iErr = Err
                    On Error GoTo 0

        Select Case iErr
                Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
                Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
                Case Else: IsFileReadOnlyOpen = 1 'Error iErr
        End Select

        End Function    'IsFileReadOnlyOpen

因此,当在 Excel VBA 中保存文件时,我会有以下内容:

        Excel.Application.DisplayAlerts = False
                    If IsFileReadOnlyOpen(myFilePathName) <> ExistsAndOpenSoBlocked Then
                               Excel.ActiveWorkbook.SaveAs myFilePathName, , , , True
                    End If
        Excel.Application.DisplayAlerts = True
于 2012-07-18T08:15:52.783 回答