Welcome to MSDN Blogs Sign in | Join | Help

Microsoft Access Team Blog

Get product announcements, tips and tricks, and news directly from the team @ Microsoft.
Running a Command as Administrator in VBA

We received a question the other day from someone who was using the Shell function in VBA to run a command in a command prompt. The command in question was netsh dhcp, but this could apply to any number of commands.

The original code was as follows:

Shell "c:\windows\system32\cmd.exe /k netsh –c dhcp"

This code had worked for a while, but on Windows Server 2008 (and presumably Windows Vista and Windows 7), this command requires elevated permissions. There are likely a few ways to do this, but we’ll look at the runas command to make this work.

The runas command allows you to start a process as another user. For our purposes, the syntax is something like:

RUNAS /user:<UserName> program

To run netsh using the runas command, you could change the code as follows:

Shell "runas /user:administrator ""c:\windows\system32\cmd.exe /k netsh –c dhcp"""

This will launch a command window and prompt you for the administrator password in the command window itself.

Another way to do this is to use "runas" as the verb for the ShellExecute API function as follows:

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
  (ByVal hWnd As Long, _
   ByVal lpOperation As String, _
   ByVal lpFile As String, _
   ByVal lpParameters As String, _
   ByVal lpDirectory As String, _
   ByVal nShowCmd As Long) As Long

Sub RunAsAdmin()
    Const SW_NORMAL As Long = 1

    ShellExecute hWndAccessApp(), _
                 "runas", _
                 "c:\windows\system32\cmd.exe", _
                 "/k netsh -c dhcp", _
                 "c:\windows\system32", SW_NORMAL
End Sub

When you run the RunAsAdmin procedure, you should be prompted by Windows to run the specified command.

Posted: Wednesday, November 11, 2009 8:23 AM by robcooper
Filed under: ,

Comments

Edwin Blancovitch said:

way to go ROB, as always great post. .

You know what, it will be great if we can have a list of some commands via API's Better that we can run from access . . .

Such as :

a) how to start a terminal services session from access

b) how to see if sql is installed

c) how to start a connection using a vpn

d) how to close a connection from a vpn

Stuff like that, will be great to have.

Edwin. . .

# November 12, 2009 10:51 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker