2017-08-09 72 views
2

當我啓動從C#我用下面的代碼過程:設置命令行選項訪問VBA

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

+0

如果您想通過使用C#與VBA中的變量進行交互,您應該閱讀[Office Interop對象](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interop/如何對接入辦公onterop對象)。這將要求您重寫問題中發佈的所有代碼,並可能在此期間修復您的錯誤 –

回答

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 
+0

如何在Access端獲取參數? – daniele3004

+0

@ daniele3004在'VBA Code'中? – Smartis

+0

是的,在VBA代碼 – daniele3004

0

,最好的辦法應該被發現將相關應用程序添加到文件類型中,然後使用您需要的參數(包括要打開的文件)啓動它。

您可以瞭解如何確定默認應用程序here