EXCEL macro : How to get user path

For VB programming, sometimes we need to specify path for ex; make dir , removing dir etc.
If you are sharing your pc it will be quite a headache since you need to specify a path for each user.

for example if I'm logging to the pc, the user path will be
"C:\Users\nidzam"
if other people logging to it, it will be
"C:\Users\other user name"

It will make no sense in programming to hard code the path each time you want to specify a directory etc.

Below code will help to show you how to get the user path
=====================================================
 Sub userpath()  
 Dim Myuser As String  
 Myuser = Environ("userprofile")  
 MsgBox ("Current user path = ") & Myuser  
 End Sub  
=====================================================
The msgbox will show as below


to get another dir path, we can combine this set of code with intended
path. For example, I want to get current user desktop path.
The code is as below
=====================================================
 Sub userDesktoppath()  
 Dim Myuser As String  
 Dim Myuserdesktop As String  
 Myuser = Environ("userprofile")  
 Myuserdesktop = Myuser & "\Desktop"  
 MsgBox ("Current user path = ") & Myuser  
 End Sub  
=====================================================

Hope you find this code useful.


No comments:

Post a Comment