使用 (ActiveWorkbook.Path) 的 VBA Excel SetCurrentDirectory 不适用于 64 位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16904231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Excel SetCurrentDirectory using (ActiveWorkbook.Path) does not work with 64-bit
提问by Josh3030150
We currently made all the changes necessary to get our VBA templates to work with Office 2010 32-bit and 64-bit. We are running into one issue that I have been trying to resolve.
我们目前进行了所有必要的更改,以使我们的 VBA 模板能够与 Office 2010 32 位和 64 位一起使用。我们遇到了一个我一直在努力解决的问题。
This is the code that used to work for just 32-bit within the DynamicXLSAppHandler:
这是曾经在 DynamicXLSAppHandler 中仅适用于 32 位的代码:
Dim L_Return As Long
'Set Current Directory in SaveAs dialog
If ActiveWorkbook.Path <> "" Then
ChDrive (ActiveWorkbook.Path)
ChDir (ActiveWorkbook.Path)
L_Return = SetCurrentDirectory(ActiveWorkbook.Path)
End If
The purpose of this code is when the user clicks on Save, or Ctrl-S, they are prompted with a SaveAs dialog in the directory (path) that they originally opened the document/template from. Without this code (because of the 64-bit incompatibility) it now just opens 'Documents' as the default and the users need to browse to the original path.
此代码的目的是当用户单击“保存”或 Ctrl-S 时,系统会提示他们在最初打开文档/模板的目录(路径)中出现“另存为”对话框。如果没有此代码(因为 64 位不兼容),它现在只是默认打开“文档”,用户需要浏览到原始路径。
I am wondering if there is a new way of doing this for 64-bit, or if I have to change things completely.
我想知道是否有针对 64 位执行此操作的新方法,或者我是否必须完全改变。
回答by JosieP
To use the SetCurrentDirectory
API in 64-bit, you need to add the PtrSafe
keywordto the function declaration:
要SetCurrentDirectory
在 64 位中使用API,您需要在函数声明中添加PtrSafe
关键字:
#If VBA7 Then
Private Declare PtrSafe Function SetCurrentDirectory Lib "kernel32" _
Alias "" SetCurrentDirectoryA(ByVal lpPathName As String) As Long
#Else
Private Declare Function SetCurrentDirectory Lib "kernel32" _
Alias "" SetCurrentDirectoryA(ByVal lpPathName As String) As Long
#End If
By the way:
顺便一提:
- Why do you need
ChDrive
andChDir
as well asSetCurrentDirectory
? ChDrive
should only be passed a drive letter, for example like this:ChDrive Left(ActiveWorkbook.Path, 1)
- 为什么你需要
ChDrive
和ChDir
以及SetCurrentDirectory
? ChDrive
应该只传递一个驱动器号,例如这样:ChDrive Left(ActiveWorkbook.Path, 1)