VB2010: Create shortcut on desktop programmatically that runs as administrator - vb.net

I am using this way below to create shortcuts on user's desktop. I also want them to run as administrator. I found this, here in StackOverflow but... I want to do the same thing programmatically, not by the hand.
Here is my code:
Private Sub CreateShortcuts()
Dim NewDir = AppFolder.Text
Dim WSH As Object = CreateObject("WScript.Shell")
WSH = CreateObject("WScript.Shell")
Dim MyShortcut, DesktopPath
DesktopPath = WSH.SpecialFolders("Desktop")
MyShortcut = WSH.CreateShortcut(DesktopPath & "\Application Controller.lnk")
MyShortcut.TargetPath = WSH.ExpandEnvironmentStrings(NewDir & "\Application.exe")
MyShortcut.WorkingDirectory = WSH.ExpandEnvironmentStrings(NewDir)
MyShortcut.WindowStyle = 1
MyShortcut.IconLocation = NewDir & "\Application.exe"
MyShortcut.Save()
End Sub

I think you are searching for the 'runas' command. You can say that your command line arguments for the target program is:
runas /savecred /user:administrator "yourprogrampathhere.exe"
Just make sure that the user named 'administrator' does exist. BTW, there is a flag on the Properties window of the shortcut, I just don't know how to do it with the WShell way, but this solution might work.
This line needs to change:
MyShortcut.TargetPath = WSH.ExpandEnvironmentStrings("runas /savecred /user:administrator """ & NewDir & "\Application.exe""")
If you're wondering why I put too many quotation marks, don't worry. They're used to escape the initial quotation mark. Have a wonderful day, and I hope your program will work!
EDIT: Using this will prompt you for an Administrator password. You must have one of that, because empty passwords are not allowed. The password will be saved and won't be prompted again until next system reboot.

Related

Trying to Open a File with a Button from Access using ShellExecute

In my Access database, I have a button on a form to open an external file.
Here is the code that I am using for that.
Private Sub btn_OpenFile_Click()
Dim a As New Shell32.Shell
Dim strPath As String
strPath = Me.Attachment
strPath = Chr(34) & strPath & Chr(34)
Call a.ShellExecute(Me.Attachment)
'Call CreateObject("Shell.Application").ShellExecute(strPath)
'MsgBox strPath
End Sub
The problem that I have is if I actually put in the value of the variable (Me.Attachment) it works fine and opens the program and the file.
For Example, If I put in Call a.ShellExecute("C:\Docs\Some File.pdf") it will open. But if I use the variable in it's place it won't open and tells me it cannot find the file. I have verified with the msgbox that it is receiving the correct information. I have tried to wrap it in quotes and have used the Chr(34) as shown above but nothing works.
How can I get that variable to work in the ShellExcute command?
I have looked through all the forums and it seems like everyone is using a string but not a variable. I don't want to use just the shell command as I don't want to track down all of the different apps people use to open different types of files. There will be different file types that will need to be opened and I thought this would be easier than it actually is.
Thank you for the help.
I'm pretty sure that ShellExecute expects a Variant parameter, not a String.
So try this:
Call a.ShellExecute(CVar(strPath))
or use a Variant variable from the start.
I had the same problem here.
Both of the following work for me:
Dim a As New Shell32.Shell
Dim strPath As String
strPath = Me.Attachment
Call a.ShellExecute(strPath)
Dim a As Shell
Dim strPath As String
strPath = Me.Attachment
Set a = CreateObject("Shell.Application")
a.ShellExecute strPath
Even referencing Attachment directly.
a.ShellExecute(Me.Attachment)

manual entry in cmd window works, VBA executing CMD works, but not VBA when I use run (so I can hide the window)

SECOND EDIT/UPDATE: tried the path change recommendations, did not see any changes to the command string, still does not work. I re-wrote the code to use a fixed text file instead of a random temp file so I could monitor the contents of the file during execution. Able to conclusively show it is the
oShellObject.Run sCommandStringToExecute & " > " & sShellRndTmpFile, 0, True
code line that doesn't behave as expected. Still works with the w32tm command line, but not with the ntpq command line. With ntpq command, no changes made to the file, no error flags. I also tried out (again) the exec version of this problem where the window is supposed to flash a bit before it gets hidden programmatically. I get the expected reslut using exactly the same command string, cut and pasted into the other code. So the same command line works with manual entry into CMD, into PowerShell, and in the .exec code version, not the .run code version.
End of second edit. -------------------
EDIT: more debugging... ntpq -p works if I do .exec instead of .run, but then of course can't hid the cmd window. Extra test code at the end.
This Works: If I run these two commands in manually opened cmd window, or PowerShell window, both give the expected results.
w32tm /stripchart /computer:time.nist.gov /dataonly /samples:3 /rdtsc /period:1
ntpq -p
The second, ntpq -p, is bundled with NTP windows software from the home of the Network Time Protocol project that gives similar information to windows' w32tm when NTP is set up to look at the same time service computer as in the w32tm command.
This Doesn't work:
When I try to use these two command string when running CMD functions hidden using the classic "write to file" method shown in SO here and other places, the w32tm version gives the same results as the manual version, but the ntpq version just returns "error".
I read every single one of the recommended links for this question as well as searching OS and Google, and have not found an answer.
I am stuck on next step to troubleshoot the problem...only thing I could think of was to run the commands manually to confirm they work there. I can't imagine it being a administrator privileges issue since I can run them both in CMD line or PowerShell windows opened at normal rights level.
What should I look at next?
Here is the test code.
Option Explicit
Sub TestShellRun()
Dim sCmd As String, sReturnNTP As String
sCmd = "w32tm /stripchart /computer:time.nist.gov /dataonly /samples:3 /rdtsc /period:1 " ' /packetinfo"
sCmd = "%ComSpec% /C %SystemRoot%\system32\" & sCmd
sReturnNTP = fShellRun(sCmd) 'good return value, same as manual cmd line
Debug.Print sReturnNTP
sCmd = "ntpq -p"
sCmd = "%ComSpec% /C %SystemRoot%\system32\" & sCmd
sReturnNTP = fShellRun(sCmd) 'ERROR return value, even though manual cmd line has good values
Debug.Print sReturnNTP
End Sub
Public Function fShellRun(sCommandStringToExecute) As String
' This function will accept a string as a DOS command to execute.
' It will then execute the command in a shell, and capture the output into a file.
' That file is then read in and its contents are returned as the value the function returns.
' "myIP" is a user-selected global variable
Dim oShellObject, oFileSystemObject, sShellRndTmpFile
Dim oShellOutputFileToRead
Dim iErr As Long
Set oShellObject = CreateObject("Wscript.Shell")
Set oFileSystemObject = CreateObject("Scripting.FileSystemObject")
sShellRndTmpFile = oShellObject.ExpandEnvironmentStrings("%temp%") & oFileSystemObject.GetTempName
On Error Resume Next
oShellObject.Run sCommandStringToExecute & " > " & sShellRndTmpFile, 0, True
iErr = Err.Number
On Error GoTo 0
If iErr <> 0 Then
fShellRun = "error"
Exit Function
End If
On Error GoTo err_skip
fShellRun = oFileSystemObject.OpenTextFile(sShellRndTmpFile, 1).ReadAll
oFileSystemObject.DeleteFile sShellRndTmpFile, True
Exit Function
err_skip:
fShellRun = "error"
oFileSystemObject.DeleteFile sShellRndTmpFile, True
End Function
sCommand = "ntpq.exe -p"
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(sCommand)
strOutput = WshShellExec.StdOut.ReadAll
Debug.Print strOutput
Your fShellRun function didn't work due to error in temporary file path. Here is fixed version.
Function fShellRun(sCommandStringToExecute) As String
...
'invalid file path without path separator between directory path and filename!
sShellRndTmpFile = oShellObject.ExpandEnvironmentStrings("%temp%") & _
oFileSystemObject.GetTempName
'valid path with path separator between directory path and filename
sShellRndTmpFile = oFileSystemObject.BuildPath( _
Environ("temp"), oFileSystemObject.GetTempName)
...
End Function

opening powerpoint using excel vba on a macintosh

I have done a lot of research on this topic, and can't seem to find anything that works for me.
What my project does is the user fills out the excel file with data. The user presses finish which takes the excel data and auto populates it into a powerpoint. The powerpoint "called "ExcelUseThisOne") is already made and is saved in a folder (called "PowerPoint") on the desktop. I want the excel file to open the powerpoint, auto populate it, save it, then close powerpoint.
I have this working on a PC, but not a Mac.
Here is my code on opening powerpoint which I thought would work, but doesn't:
UserName = InputBox(Prompt:="You name please.", Title:="ENTER YOUR NAME", Default:="all LOWERCASE and ONE WORD")
Dim strPresPath As String, strExcelFilePath As String, strNewPresPath As String
strPresPath = ":Users:" & UserName & ":Desktop:PowerPoint:ExcelUsesThisOne.ppt"
FilePath = ":Users:" & UserName & ":Desktop:PowerPoint:NewPresentation.ppt"
strNewPresPath = FilePath
Set oPPTApp = CreateObject("PowerPoint.Application")
oPPTApp.Visible = msoTrue
Set oPPTFile = oPPTApp.Presentations.Open(strPresPath)
Any help would be great! Thank you.
I'm not certain but I seem to recall that Mac does not use file extensions, so you could try this on Mac:
strPresPath = ":Users:" & UserName & ":Desktop:PowerPoint:ExcelUsesThisOne"
Other possible reason is that the username has been entered incorrectly? I think this will work on a mac, instead of the input box you can try one of these options:
strPresPath = ":Users:" & Environ("username") & ":Desktop:PowerPoint:ExcelUsesThisOne"
Or try that approach with the file extension (again, I'm not 100% certain about the file extensions not used on Mac OS).
You may need to volume name, e.g.,:
strPresPath = "volume_name:Users:..."`
Otherwise, you can debug by checking the path of some other workbook, which should show you the correct way to formulate the path string.
Good luck!

Excel VBA error using WScript.Shell.Run

After recently upgrading from Excel 2010 to Excel 2013, I moved a custom add-in (.xlam) to the new Application.LibraryPath directory (C:\Program Files\Microsoft Office 15\root\office15\Library\BTRTools). There is a bit of code that launches an executable (exe) file (located in sub directory of the add-in). However, since the upgrade/move, I am not getting an error:
PrettyPrintXml.exe - Application Error
The application was unable to start correctly (0xc000007b). Click OK to close the application.
I'm obviously pretty convinced it is file permissions. I have explicitly added myself permissions with full rights to the \Library folder (and all subs). Note that I think I had to do this even with Excel 2010 (folder at C:\Program Files (x86)\Microsoft Office\Office14\Library) to make things work.
However, after all this, I'm still stuck and can not launch the exe file. Any ideas/suggestions on how to make this work?
Code is pretty standard:
Public Sub RunShellExecute(sFile As String, Optional params As String = "", Optional wait As Boolean = False)
Dim wsh As Object: Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = wait
Dim windowStyle As Integer: windowStyle = 1
Dim exe As String: exe = IIf(Left(sFile, 1) <> """", """" & sFile & """", sFile)
Dim exeParams As String: exeParams = IIf(params <> "", " " & params, "")
Dim errorCode As Integer: errorCode = wsh.Run(exe & exeParams, windowStyle, waitOnReturn)
If errorCode = 0 Then
'// MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
End Sub
I know your question is "Why doesn't this work", but I thought you might be interested in an alternate solution: There is a native VBA PrettyPrintXML. You need to add a reference to the MSXML library in your VBA project by clicking "Tools" ---> "References..." and then check the box next to Microsoft XML, v6.0 (or whatever version is included with your version of Office/Windows).
Please change the title of your question, because Excel VBA is able to use WScript.Shell.Run, otherwise you wouldn't be getting your error.
As for the actual issue, this looks like a 32-bit / 64-bit problem. Investigate whether the program you're calling is appropriate for your system and whether it tries to load the right DLLs.
The problem is not file permissions, then you would get a different status code.
You should use a path without spaces in it, something simple like 'C:\BTRTools'. Then it should work.

Issue with an LPR Command in VB

I am creating a VB app which will "move" xls reports from a directory to a ReportSafe app. I am also working in an existing VB app which does just that, so I am using it for reference.
It isn't as simple as moving files from one directory to another, because ReportSafe requires an lpr command to tell it (ReportSafe) which file to pick up.
Here is what I have so far:
Imports System.IO
Module Module1
Sub Main()
''Declarations
Dim Files As ArrayList = New ArrayList()
Dim FileName As String
''Write All Files in *directory* to ReportSafe
Files.Clear()
Files.AddRange(Directory.GetFiles(*directory*))
For Each FileName In Files
Dim RPname As String
Dim RealName As String
RPname = FileName.ToString
RealName = "/"
RealName = RealName & RPname.Remove(0, 34)
Dim a As New Process
a.StartInfo.FileName = "C:\Windows\system32\lpr.exe"
a.StartInfo.Arguments = "-S*ServerName* -Plp -J" & Chr(34) & RealName & Chr(34) & " " & Chr(34) & RPname & Chr(34)
a.StartInfo.UseShellExecute = False
Next
End Sub
End Module
The whole lpr command/arguments are throwing me for a loop. I'm not sure if my question is specific to ReportSafe, and if that's the case, I may be out of luck here. I have pulled this code from the already existing app which moves reports to ReportSafe, and adjusted for my own use, but no luck so far.
FYI, I had to turn on LPR Monitor services to obtain to the lpr.exe
Questions:
What are the proper arguments to pass through to this lpr command?
Is there a problem with the logic that is causing the issue?
I continued to tinker and look at my reference code and discovered some flaws in logic:
For one, the report name I was passing did not include the complete file path.
Another thing is that I never started the process with a.Start(). Rookie mistakes for sure... haha