我正在写一些宏用于一般用途。我有一个应该在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下运行?
您只能在编译器条件中使用编译器常量。这意味着您必须在部署之前调整常量值,如下所示:
'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