首页 > 解决方案 > 在不打开文件的情况下使用 VBA 检测 Excel 文件是否具有 IRM(信息权限管理)限制

问题描述

我有一个使用 VBA 用 Microsoft Access 编写的应用程序,它打开 Excel 文件,以各种方式处理内容,然后关闭它们。如果无法打开文件,那么我需要检测到这一点并跳过该文件,否则应用程序将有效冻结。

Excel 文件来自多个来源,如果它们受到限制,我没有打开它们的帐户凭据。

使用受密码保护的文件,我可以提供不正确的密码,检测错误然后跳过该文件。

Application.Workbooks.Open(FileName, False, , , "xxxx", , True)

如果 Excel 文件已应用 IRM(信息权限管理)限制,则当您在 Excel 应用程序中打开文件时,系统会提示您使用有权打开文件的帐户登录 Excel。

IRM 文件的帐户登录提示

如果您尝试在 Excel 应用程序不可见的情况下使用上述 VBA 代码打开文件,则该过程将停止并且不会产生错误。

我需要做的是在尝试打开文件之前检测文件是否应用了 IRM,或者尝试打开它并生成我可以检测到的错误。

在此先感谢您提供解决此问题的任何帮助。

标签: excelvbams-access

解决方案


在尝试了多种方法后,我发现受限文件包含一个字符串,表明它们受到权限管理的保护。

因此,如果您打开文件并检查内容,您可以检测它是否受到限制,而无需尝试将其加载到 Excel 中。

此功能适用于我尝试过的所有文件。

Function IsFileRestriced(FileName As String) As Boolean

   Dim lngFile As Long, lngPos As Long
   Dim strContent As String

   'Open the file in binary mode
   lngFile = FreeFile
   Open FileName For Binary As lngFile

   'Read the whole file into a string
   strContent = Space$(LOF(lngFile))
   Get #lngFile, , strContent

   'Check if the file has the rights management string
   lngPos = InStr(1, strContent, "Microsoft Rights Label")

   'Close the file
   Close #lngFile

   'Return the result
   If lngPos > 0 Then IsFileRestriced = True

End Function

推荐阅读