为Windows和Mac指定VBA中用户文件夹的路径

And*_*ott 4 macos excel vba excel-vba excel-vba-mac

我正在编写一个使用VBA从Excel生成文件的工具.生成的文件将写入用户的Documents文件夹中的文件夹(如果存在).

例如 C:\Users\<username>\Documents\Some Folder\

如果最后一个文件夹不存在,则VBA会创建它.我使用以下行来确保文件夹的位置适用于组织中分布的不同Windows用户:

If Len(Dir(Environ("USERPROFILE") & "\Documents\Some Folder", vbDirectory)) = 0 Then
    MkDir Environ("USERPROFILE") & "\Documents\Some Folder"
End If
Open Environ("USERPROFILE") & "\Documents\Some Folder\" & "file.php" For Output As #1
Print #1, output
Close
Run Code Online (Sandbox Code Playgroud)

我现在的问题是我还必须为Mac OSX用户提供服务.目前我无法访问Mac进行测试,但我认为上述操作无效.

我可以用什么来指向用户文档中的子文件夹,以及如何包含有条件地使用Windows行或Mac行的代码?

Vin*_*t G 8

有条件编译允许您根据您使用的操作系统编译不同的代码.有关条件编译,请参阅此页面.

在您的情况下,您需要附上Mac的Windows特定代码:

#if Mac then
'here Mac only code
#else
'here Windows only code
#end if
Run Code Online (Sandbox Code Playgroud)

我自己没有Mac测试,但根据这个站点,您可以使用MacScript函数获取请求的文件夹路径,并在参数中传递正确的脚本.


Chr*_*007 6

您有两种选择:

1.使用Application.PathSeparator... 请在此处查看MSDN.

码:

Dim PS as String
PS = Application.PathSeparator
If Len(Dir(Environ("USERPROFILE") & PS & "Documents" & PS & "Some Folder", vbDirectory)) = 0 Then
    MkDir Environ("USERPROFILE") & PS & "Documents" & PS & "Some Folder"
End If
Open Environ("USERPROFILE") & PS & "Documents" & PS & "Some Folder" & PS & "file.php" For Output As #1
Print #1, output
Close
Run Code Online (Sandbox Code Playgroud)

2.创建一个IF THEN检查OS

码:

Sub SaveDoc()
    Dim wksSheet As Worksheet

    If InStr(1, Application.OperatingSystem, "Windows") > 0 Then
      'Code with Windows Path Separator
      Exit Sub

    Else
      'Code with Mac Path Separator
      Exit Sub
    End If

End Sub
Run Code Online (Sandbox Code Playgroud)

  • @ Chrismas007`TheOS`变量在这里完全是多余的.您应该立即执行`InStr(1,Application.OperatingSystem,"Windows")> 0`. (3认同)
  • `Environ("USERPROFILE")` 在 Mac 上有效吗? (2认同)