creating shortcut of current excel file in startup folder using VBA - getting error saying can't save

opinionated86

New Member
Joined
Feb 2, 2016
Messages
12
I've created the following macro (from bits and bobs on forums) to save a shortcut of the current file in the startup folder of my computer, if i just manually create a shortcut it works so i know i can edit this folders contents but when i run this macro it produces and error about not being able to save shortcut. Any help would be great.

Code:
Sub new_flexi_user()startup = "C:\Users\" & UserName & "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\" & Replace(ThisWorkbook.Name, ".xlsm", ".lnk")


Dim sShortcutLocation As String


sShortcutLocation = startup
With CreateObject("WScript.Shell").CreateShortcut(sShortcutLocation)
    .TargetPath = ThisWorkbook.FullName
    .Description = "Shortcut to the file"
    .Save
End With


End Sub

Thanks
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.
Hi

from the code posted, the problem lies with the reference to 'USERNAME' (which isn't set). revised code follows (which works for me!)

Code:
Sub new_flexi_user()

startup = "C:\Users\" & Environ("UserName") & "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\" & Replace(ThisWorkbook.Name, ".xlsm", ".lnk")

Dim sShortcutLocation As String

sShortcutLocation = startup
With CreateObject("WScript.Shell").CreateShortcut(sShortcutLocation)
    .TargetPath = ThisWorkbook.FullName
    .Description = "Shortcut to the file"
    .Save
End With

End Sub
 
Upvote 0
Sorted now, hate to admit it but you were totally right, ditsy me, i have 'username' as a public function on most of my projects but hadn't created it on this one.
Thanks
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,594
Messages
6,120,436
Members
448,964
Latest member
Danni317

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top