我正在编写一些用于一般用途的宏。我有一个应该在Access和Excel下可执行的宏。我尝试了以下想法。
#If Application.Name = "Microsoft Excel" Then
sFile = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, ".")) & "foo"
#ElseIf Application.Name = "Microsoft Access" Then
sFile = Left(CurrentDb.Name, InStrRev(CurrentDb.Name, ".")) & "foo"
#End If
当然这不起作用。对象Application在编译时不存在。我的问题是,是否有一个常量表明宏在Access或Excel下运行?
答案 0 :(得分:4)
您只能 在编译器条件下使用编译器常量。这意味着您必须在部署之前调整常量值,如下所示:
'Requires References to BOTH Excel AND Excel
#Const AccessHost = False
#Const ExcelHost = True
#If ExcelHost Then
sFile = Left(ThisWorkbook.FullName, InStrRev(ThisWorkbook.FullName, ".")) & "foo"
#ElseIf AccessHost
sFile = Left(CurrentDb.Name, InStrRev(CurrentDb.Name, ".")) & "foo"
#End If
如果你想要更有活力的东西,并且你没有早期绑定引用Excel和Access,那么你不需要编译器指令,但你需要使用后期绑定来制作它适用于两个主机:
Dim app As Object 'Late-binding
Set app = Application
If app.Name = "Microsoft Excel" Then
sFile = Left(app.ThisWorkbook.FullName, InStrRev(app.ThisWorkbook.FullName, ".")) & "foo"
ElseIf app.Name = "Microsoft Access" Then
sFile = Left(app.CurrentDb.Name, InStrRev(app.CurrentDb.Name, ".")) & "foo"
End If