2017-02-24 38 views
0

我想用Access 2016作爲數據庫的前端,當用戶點擊一個按鈕時,它會生成一個Powershell腳本並運行它。VBA訪問寫入PS1文件

我目前使用這樣的:

Dim Script As String 
Script = ("test" & vbCrLf & "2nd line?") 
Set f = fileSysObject.OpenTextFile("C:\Users\%Username%\Documents\Access.ps1", True, True) 
f.Write Script 
f.Close 

然後運行該腳本,我使用:

Dim run 
run = Shell("powershell ""C:\Users\%Username%\Documents\Powershell\Access.ps1""", 1) 

我意識到,這可能是這樣做的一個非常糟糕的方式!所以,任何幫助非常感謝!

謝謝!編輯: 對不起,這是沒有問題的!

的問題是,它突出在「f.write腳本」

編譯錯誤的錯誤:未找到方法或數據成員。

+1

_我意識到這可能是一個非常糟糕的做法!_ - 是什麼讓你這麼想?它會導致錯誤嗎?它是否會導致一些其他不良行爲? StackOverflow並不適合這類開放式問題;主題問題是那些有特定問題的問題。 –

+0

幫助什麼?這篇文章中沒有任何問題。 –

回答

0

%VAR%不VBA工作的格式,你需要Environ("VAR")

這就是說用戶名不與該方法返回一個值,但你可以在這種情況下使用VBA.Environ("Username")

Dim strScript, strUserName, strFile As String 
Dim objFSO, objFile as Object 

Set objFSO = CreateObject("Scripting.FileSystemObject") 

strScript = ("test" & vbCrLf & "2nd line?") 
strUserName = VBA.Environ("Username") 
strFile = "C:\Users\" & strUserName & "\Documents\Access.ps1" 

Set objFile = objFSO.CreateTextFile(strFile) 
objFile.WriteLine strScript 
objFile.Close 

Set objFSO = Nothing 
Set objFile = Nothing 
+0

腳本,UsrName目前被定義爲Variant。也許將它們定義爲字符串。另外,f和filesysObject在哪裏定義? –

+0

我認爲OP只包含了他的腳本的相關部分,可能並非如此,所以我已經充實了我的答案。 –