3

I have an Excel file with VBA written on it that draws information from a file on my computer. The Excel file is on a network folder and I would like for other users on the network to use it as well. However, I have hardcoded the file path on the VBA and, as such, whenever another user opens it, it looks for a file that is not available.

This is the path I would like to change:

C:\Users\User1\Documents\The Market in\DATA FOR REPORTS.xlsx

The only difference on the paths would be the user's name: User1, user2, etc.

How can I write the VBA code in order for it to replace the username in the file path with the Windows user name opening it?

I have tried to use wild card and also tried to use ENVIRON("username") but have not been successful.

The code I want to replace is what's below:

Private Sub Workbook_Open()

Application.Visible = False
WelcomeForm.Show
Workbooks.Open ("C:\Users\User1\Documents\The Market in\DATA FOR REPORTS.xlsx")

End Sub

This is what I did using ENVIRON:

Private Sub Workbook_Open()

Dim username As String

username = Environ("username")

Application.Visible = False
WelcomeForm.Show
Workbooks.Open ("C:\Users\&username&\Documents\The Market in\DATA FOR REPORTS.xlsx")

End Sub

Thank you very much

3
  • 1
    Environ("Username") should work. Can you show how did you use it and what was the problem/error? Commented Aug 25, 2017 at 13:11
  • I've just added it to the question. Thank you or your help! Commented Aug 25, 2017 at 13:20
  • This is not correct concatenation syntax - "C:\Users\&username&\Documents - look carefully at the answer below Commented Aug 25, 2017 at 13:43

2 Answers 2

8

Try something like this:

Private Sub Workbook_Open()
   Application.Visible = False
   WelcomeForm.Show
   Workbooks.Open ("C:\Users\" & Environ("UserName") & "\Documents\The Market in\DATA FOR REPORTS.xlsx")
End Sub
Sign up to request clarification or add additional context in comments.

Comments

2

Environ("userprofile") will return the path & username.
On my PC it returns C:\Users\darren.bartrup-cook

Another way is:
CreateObject("WScript.Shell").SpecialFolders("MyDocuments")
On my PC this returns C:\Users\darren.bartrup-cook\Documents

You could use it like this:

Private Sub Workbook_Open()

    Dim wrkBK As Workbook
    Dim DocFldr As String

    DocFldr = CreateObject("WScript.Shell").SpecialFolders("MyDocuments")

    Set wrkBK = Workbooks.Open(DocFldr & "\The Market in\DATA FOR REPORTS.xlsx")

    MsgBox wrkBK.Name & " is open", vbOKOnly + vbInformation

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.