我当前正在使用类似于以下内容的 VBA 代码来指定共享库的位置,以用于从 Office 应用程序到桌面应用程序的通信(传递字符串)。 VBA 代码/宏需要存在于加载项 (.ppa) 中。
Private Declare Sub sharedLibPassString CDecl Lib "/Users/myUserName/Library/Application Support/myCompanyName/MySharedLib.dylib" Alias "PassString" (ByVal aString As String)
在 VBA 宏的代码中,我可以执行以下操作。
Call sharedLibPassString(myString)
我已经可以进行通信,但我想将 /Users/myUserName/
部分替换为当前用户的主目录。通常在 Mac 上,您会指定 ~/Library/Application Support/...
,但 ~/
语法不起作用,会生成“找不到文件” “运行时错误。
我发现使用以下环境变量方法可以获得我需要的 ~/
位置:
Environ("HOME")
但是,我没有找到一种方法来使这部分成为 CDecl Lib
语句,因为据我所知,Environ
是在运行时评估的.
有没有办法在 VBA 中指定共享库在用户主目录 (~/
) 中的位置?
以下是关于我的环境/方法的一些注释:
- 我使用的是 Mac,但我相信如果有解决方案,它在 PC 上也会类似。
- 我认为这并不重要,但我使用的 Office 应用程序是 PowerPoint (2011)。
- 我尝试访问应用程序支持目录内的区域而不是共享库的默认位置的原因是因为我希望桌面应用程序将共享库放置在没有安装程序的位置,并且无需用户或管理员的权限。如果有更好的解决方案或位置来完成相同的任务,这也会非常有帮助。
最佳答案
抱歉回复太长,我只是想确保我已经很好地解释了这一点。
从此页面(Anatomy of a Declare Statement)我们读到了
The Lib keyword specifies which DLL contains the function. Note that the name of the DLL is contained in a string within the Declare statement. (emphasis added)
根据实验,如果我尝试提供除字符串常量之外的任何内容,VBE 会责骂我。
据我所知,唯一的解决方法需要在运行时重写字符串常量。
以下是如何完成此操作的示例:假设您的声明语句位于当前项目的 Module1 中,并且您故意以这种格式在模块顶部编写声明:
Private Declare Sub sharedLibPassString CDecl Lib _
"/Users/myUserName/Library/Application Support/myCompanyName/MySharedLib.dylib" _
Alias "PassString" (ByVal aString As String)
您可以通过代码访问该模块(需要开发人员宏设置下列出的信任中心中的 VBA 权限):
Dim myModule
set myModule = ActivePresentation.VBProject.VBComponents("Module1").CodeModule
获得CodeModule后,可以直接替换第二行:
myModule.ReplaceLine 2, Environ("HOME") & " _"
任务完成!
如果您这样做,您将需要在尝试调用您声明的子程序之前更新路径。执行中必须有一个中断,以便 VBA 能够识别更改。此外,在中断模式下您将无法修改代码。
现在,如果我这样做,我想确保替换正确的行,以免破坏代码。您可以通过调用 myModule.Lines(2,1)
来检查第二行的内容,它将返回该行的字符串值。
但是,这里有一个更强大的解决方案,它将找到正确的行,然后替换它(假设 myModule 已按上面列出的方式定义):
Dim SL As Long, EL As Long, SC As Long, EC As Long
Dim Found As Boolean
SL = 1 ' Start on line 1
SC = 1 ' Start on Column 1
EL = 99999 ' Search until the 99999th line
EC = 999 ' Search until the 999th column
With myModule
'If found, the correct line will be be placed in the variable SL
'Broke search string into two pieces so that I won't accidentally find it.
Found = .Find("/Users/myUserName/Library/Application Support/myCompanyName/" & _
"MySharedLib.dylib", SL, SC, EL, EC, True, False, False)
If Found = True Then
'Replace the line with the line you want, second paramater should be a string of the value.
.ReplaceLine SL, Environ("HOME") & " _"
End If
End With
关于vba - 是否可以在 VBA(在 Office for Mac 中)中为共享库指定用户主目录中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13139109/