Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify path to user folder in VBA for both Windows and Mac

Tags:

macos

excel

vba

I am writing a tool which generates a file from Excel using VBA. The generated file is written to a folder, if it exists, in the user's Documents folder.

e.g. C:\Users\<username>\Documents\Some Folder\

If the last folder doesn't exist, then VBA creates it. I use the following line to ensure that the location of the folder works for different Windows users distributed in the organisation:

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

My issue now though is that I also have to cater for Mac OSX users. At present I don't have access to a Mac to test, but I am assuming the above won't work.

What could could I use to point to the sub-folder in the user's documents, and how can I include code which conditionally uses either the Windows line or the Mac line?

like image 686
Andrew Abbott Avatar asked Oct 19 '16 12:10

Andrew Abbott


People also ask

What is dir () in VBA?

Dir returns the first file name that matches pathname. To get any additional file names that match pathname, call Dir again with no arguments.

How do I insert and run VBA code in Excel for Mac?

Insert VBA code to Excel Workbook Open your workbook in Excel. Press Alt + F11 to open Visual Basic Editor (VBE). Right-click on your workbook name in the "Project-VBAProject" pane (at the top left corner of the editor window) and select Insert -> Module from the context menu.


1 Answers

You have two options:

1. Use Application.PathSeparator... See the MSDN here.

Code:

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

2. Create an IF THEN to check for OS

Code:

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
like image 102
Chrismas007 Avatar answered Nov 16 '22 02:11

Chrismas007