设置Access VBA的命令行选项

时间:2017-08-09 12:52:01

标签: c# vba ms-access access-vba

当我从C#启动进程时,我使用以下代码:

ProcessStartInfo psi = new ProcessStartInfo(@"C:\MyProgram.exe");
psi.Arguments = "1";
Process p = Process.Start(psi);

可以在VBA代码中设置全局变量的值吗?

ProcessStartInfo psiMDB = new ProcessStartInfo(@"C:\MyProgram.mdb");
psiMDB.Arguments = "1";
Process p = Process.Start(psiMDB);

如果我尝试设置参数我有这个错误:

enter image description here

2 个答案:

答案 0 :(得分:2)

您需要将您的MS Access路径与数据库作为参数组合。

string dbPath = @"c:\MyProgram.mdb";
string pathToAccess = @"C:\Program Files (x86)\Microsoft Office\root\Office16\MSACCESS.EXE";

ProcessStartInfo psiMDB = new ProcessStartInfo(pathToAccess);
psiMDB.Arguments = dbPath + " /cmd 1";
Process p = Process.Start(psiMDB);

在放入下一个参数之前,请不要忘记附上/cmd

用于读取启动参数的其他VBA代码

Option Compare Database

Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As Long)

Sub PrintStartupArguments()
    MsgBox CmdLineToStr()
End Sub

Function CmdLineToStr() As String

Dim Buffer() As Byte
Dim StrLen As Long
Dim CmdPtr As Long

CmdPtr = GetCommandLine()
If CmdPtr > 0 Then
  StrLen = lstrlenW(CmdPtr) * 2
  If StrLen > 0 Then
    ReDim Buffer(0 To (StrLen - 1)) As Byte
    CopyMemory Buffer(0), ByVal CmdPtr, StrLen
    CmdLineToStr = Buffer
  End If
End If

End Function

答案 1 :(得分:0)

最好的方法应该是找到文件类型的关联应用程序,然后使用您需要的参数启动它(包括要打开的文件)。

您可以了解如何确定默认应用here