使用 (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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:26:20  来源:igfitidea点击:

VBA Excel SetCurrentDirectory using (ActiveWorkbook.Path) does not work with 64-bit

excelvba32bit-64bit

提问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 SetCurrentDirectoryAPI in 64-bit, you need to add the PtrSafekeywordto 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 ChDriveand ChDiras well as SetCurrentDirectory?
  • ChDriveshould only be passed a drive letter, for example like this:

    ChDrive Left(ActiveWorkbook.Path, 1)

  • 为什么你需要ChDriveChDir以及SetCurrentDirectory
  • ChDrive应该只传递一个驱动器号,例如这样:

    ChDrive Left(ActiveWorkbook.Path, 1)