捕获 .XLAM 的 FileFormat 属性 而不会与 .XLSM 混淆

Catching FileFormat property of .XLAM without confusion with .XLSM

上下文

我开发了一个 .xlam 加载项,其中包含用户数据。换句话说,用户可以决定通过 ThisWorkbook.IsAddIn = False 来显示加载项文件以编辑内容,这对加载项本身具有功能。

但是,当用户s/she处理加载项的电子表格而不是普通工作簿时,他不应该能够执行某些操作其中加载项是 运行ning。

需要检查文件扩展名

从这里开始,我需要检查文件扩展名并在调用某些特定 "forbidden" 过程时对其进行验证。我做了以下测试:

混乱的根源

这不是我所期待的。当加载项设置为可见时,只需执行 FullName 请求 :

ThisWorkbook.IsAddIn = False
MsgBox ThisWorkbook.FullName

我可以看到我的文件仍然命名为 C:\myFile.xlam,即使在那一刻对用户可见。因此,即使在 运行 时间可见,我也希望 ThisWorkbook.FileFormat 引发 55。但它显然不会那样做。

问题

我需要确保区分 对加载项 (.xlam) 的修改和 对用户创建的可能 .xlsm 文件的修改,从中使用我的加载项。 为什么我的加载项的 FileFormat 等于 xlsm 中的一个,如果文件显然 xlam 关联的是 55 而不是 52?我哪里错了?

编辑 - 禁止操作示例

功能区上有一个从加载项创建和添加的按钮,它连接到一个宏,不能运行 到加载项。所以我想到的支票是这样的:

If ActiveWorkbook.FileFormat = 55 Then
    Exit Sub
End If 

但是,正如上面所说,这个检查不会被执行,因为加载项在设置为.IsAddIn = False的时刻有FileFormat = 52;因此,即使 ActiveWorkbook 是我 而不是 想要 运行 宏的加载项,检查也会失败并且宏会 运行 无论如何。

.IsAddIn workbook property simply indicates whether the file is being run as an Add-in。它不会更改文件格式。来自文档:

When you set this property to True, the workbook has the following characteristics:

  • You won’t be prompted to save the workbook if changes are made while the workbook is open.
  • The workbook window won’t be visible.
  • Any macros in the workbook won’t be visible in the Macro dialog box (displayed by pointing to Macro on the Tools menu and clicking Macros).
  • Macros in the workbook can still be run from the Macro dialog box even though they’re not visible. In addition, macro names don’t need to be qualified with the workbook name.
  • Holding down the SHIFT key when you open the workbook has no effect.

我感觉到这是您要解决的真正问题:

However, the user should not be able to perform some operations when he's/she's working on the add-in's spreadsheets rather than on the normal workbook where the Add-In is running.

如果您可以指定要限制的操作,也许会更好?可能有更好的方法来解决这个问题。

目前我找到了四种可能的解决方案,我将post放在这里以防万一有人遇到我同样的问题:

比较全名 - 感谢 Tim Williams

如果全名不同"special code"不能运行:

If ActiveWorkbook.FullName = ThisWorkbook.FullName Then
    Exit Sub
End If
'"special code"

比较 isAddIn 属性 - 感谢 David Zemens

如果此工作簿当前不是加载项,"special code" 不能 运行:

If ThisWorkbook.IsAddIn = False Then
    Exit Sub
End If
'"special code"

比较两个对象

如果活动工作簿是加载项工作簿,"special code"不能运行

If ActiveWorkbook Is ThisWorkbook Then
    Exit Sub
End If 
'"special code"

正在检查 "xlam" 扩展名

如果文件的扩展名是xlam,"special"代码将不会是运行:

If Right(ActiveWorkbook.FullName,4) = "xlam" Then
    Exit Sub
End If

上面的四种解决方案都可以很好地达到目的,但问题仍然存在:为什么 FileFormat 属性 会根据 [=15= 改变同一个文件] 是 False 而不是 True?