The below script saves a workbook to the desktop of user 123456.
Is there a way to write the code so that the workbook will be saved to any users desktop?
ActiveWorkbook.SaveAs FileName:="C:\Users\123456\Desktop\Test.xlsx", _ FileFormat:=xlWorkbookDefault, CreateBackup:=False
Maybe:
ActiveWorkbook.SaveAs FileName:="C:\Users\" & _ Application.UserName & _ "\Desktop\Test.xlsx", _ FileFormat:=xlWorkbookDefault, CreateBackup:=False
Regards
TMShucks, I tried your suggestion before starting the thread. It didn't work.
The below code saves the workbook into the Documents folder of any user.
ActiveWorkbook.SaveAs FileName:="Test.xlsx", _ FileFormat:=xlWorkbookDefault, CreateBackup:=False
sub snb() ActiveWorkbook.SaveAs CreateObject("wscript.shell").specialfolders("desktop") & "\Test.xlsx", xlWorkbookDefault end sub
snb, thanks a lot. That did it.
Sorry, I was making the naive assumption that the user name and the application user name were the same. Clearly, not ;-)
If you need the logged in user name you can get it with the following code ... but that is just a little longer than snb's code (why is that not a surprise)
Regards
Option Explicit Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long Function UserNameWindows() As String Dim lngLen As Long Dim strBuffer As String Const dhcMaxUserName = 255 strBuffer = Space(dhcMaxUserName) lngLen = dhcMaxUserName If CBool(GetUserName(strBuffer, lngLen)) Then UserNameWindows = Left$(strBuffer, lngLen - 1) Else UserNameWindows = "" End If End Function Sub test() ActiveWorkbook.SaveAs Filename:="C:\Users\" & _ UserNameWindows & _ "\Desktop\Test.xlsm", _ FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False End Sub
@TMS
Are you familiar with:
environ("username") and createobject("wscript.network").username
@snb: the first one yes, the second one, no.
I learned and used the Function GetUserName method a long time ago and tend to resort to "what I know". As ever, good to have some options.
Thank you for the reminder and the lesson ;-)
Regards
@TMS
You're welcome.
TMShucks, your lenghty code kind of made me worry that it was a bit premature to call the problem solved. I had not tried snb's code on a different computer using a different user name.
Now, I did. snb's solution works for any user on any computer.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks