The "My Documents" folder path contains a variable username component and changes from one user to another. It is possible to write a code in VBA or VB6 to access the "My Documents" folder regardless of the username, with the help of functions that can read environment variables in VB6. As with every programming language,writing code in VB6 or VBA requires knowledge of basic programming concepts including subroutines, loops, and specific VB6 functions.Environment functions such as Environ$ which receives the value of an environment variable, can be used to write a code to read environment variables in VB6.
As displayed in Windows Explorer, the My Documents folder appears to be in the root, but this is not the case. It is located in a subdirectory of C:\Documents and Settings. The problem is that this subdirectory takes the user's name and is changed not only from one PC to another, but also on PCs supporting multiple users.The following codes allow you to access the My Documents folder by default regardless of the user logged on.
Option Explicit
Private Type SHITEMID
cb As Long
abID As Byte
End Type
Private Type ITEMIDLIST
mkid As SHITEMID
End Type
Private Const CSIDL_PERSONAL As Long = &H5
Private Declare Function SHGetSpecialFolderLocation Lib "shell32.dll" _
(ByVal hwndOwner As Long, ByVal nFolder As Long, _
pidl As ITEMIDLIST) As Long
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" _
ByVal pidl As Long, ByVal pszPath As String As Long
Public Function Rep_Documents() As String
Dim lRet As Long, IDL As ITEMIDLIST, sPath As String
lRet = SHGetSpecialFolderLocation(100&, CSIDL_PERSONAL, IDL)
If lRet = 0 Then
sPath = String$(512, Chr$(0))
lRet = SHGetPathFromIDList(ByVal IDL.mkid.cb, ByVal sPath)
Rep_Documents = Left$(sPath, InStr(sPath, Chr$(0)) - 1)
Else
Rep_Documents = vbNullString
End If
End Function
To call the function, simply create a button and paste in the following code:
Private Sub CommandButton1_Click()
Cells(5, 2) = Rep_Documents()
End Sub
Dim sPathUser as String
sPathUser = Environ$("USERPROFILE") & "\my documents\"
MsgBox sPathUser