2010-07-06 106 views
0

假設我想在一個外部程序中編寫一個VBA代碼,該代碼打開一個Excel文件,運行一個宏,保存(並且對任何彈出窗口說是)並關閉Excel。是否有可能這樣做?如果是這樣,我將如何去實施它?是否可以通過外部命令在Excel中運行宏?

+0

你知道什麼類型/多少彈出窗口會出現? – Fionnuala 2010-07-06 08:49:51

+0

嗨,你說「外部程序」是什麼意思?它是Excel嗎? – Trefex 2010-07-06 09:41:02

回答

4

您可以啓動Excel,打開工作簿,然後從VBScript文件中操作工作簿。

將以下代碼複製到記事本中。

更新'MyWorkbook.xls'和'Sheet1'參數。

用vbs擴展名保存並運行它。

Option Explicit 

On Error Resume Next 

ExcelMacroExample 

Sub ExcelMacroExample() 

    Dim xlApp 
    Dim xlBook 

    Set xlApp = CreateObject("Excel.Application") 
    Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls") 
    xlBook.Sheets("Sheet1").Cells(1, 1).Value = "My text" 
    xlBook.Sheets("Sheet1").Cells(1, 1).Font.Bold = TRUE 
    xlBook.Sheets("Sheet1").Cells(1, 1).Interior.ColorIndex = 6 
    xlBook.Save 
    xlBook.Close 
    xlApp.Quit 

    Set xlBook = Nothing 
    Set xlApp = Nothing 

End Sub 

上面這個代碼啓動Excel打開工作簿,在單元格A1中輸入一個值,使其變爲粗體並更改單元格的顏色。該工作簿然後保存並關閉。然後關閉Excel。

+1

如何使用上述代碼運行存儲在工作簿中的宏? – Nerdtron 2011-12-16 15:34:37

+1

http://stackoverflow.com/q/10232150/1303610檢查了這一點。 – 2012-05-09 17:27:08

0

根據您試圖實現的目標,您還可以通過(OLE)Automation從另一個應用程序(例如Access或Word)或從另一個環境(如Visual Basic(6)中編寫的自己的應用程序控制Excel。通過.Net使用您選擇的語言來實現這一點也是可能的(儘管有些比其他語言更容易實現)。

想要從外部應用程序控制Excel還是僅從外部觸發現有工作簿中的VBA宏?

再次,根據您的意圖,工作簿可能會有一個自動打開宏,它可能是基於外部值(例如ini文件或數據庫值)的條件運行。

0

我可以想到幾種方法來做到這一點。

You can start excel by creating a file with NotePad or a similar text editor. 

Here are some steps: 

    Launch NotePad 
    Add the following line of text. Replace test.xlsm with the name and path for your file: 
    start Excel.exe "C\test.xlsm" 
    Save the file as "Test.bat". 
    Run the batch file. 
    The batch file should launch Excel and then open your file. The code in your workbook should run 

OR

再次,使用記事本。

Option Explicit 

On Error Resume Next 

ExcelMacroExample 

Sub ExcelMacroExample() 

    Dim xlApp 
    Dim xlBook 

    Set xlApp = CreateObject("Excel.Application") 
    Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls", 0, True) 
    xlApp.Run "MyMacro" 
    xlApp.Quit 

    Set xlBook = Nothing 
    Set xlApp = Nothing 

End Sub 

或者,這個。

'Code should be placed in a .vbs file 
Set objExcel = CreateObject("Excel.Application") 
objExcel.Application.Run "'C:\Users\Ryan\Desktop\Sales.xlsm'!SalesModule.SalesTotal" 
objExcel.DisplayAlerts = False 
objExcel.Application.Quit 
Set objExcel = Nothing 

現在,這是不是「外部命令」,但Windows任務調度會做打開該文件爲你的一個不錯的工作,一旦被打開,你可以運行像一個小腳本你看到下面的一個。

Private Sub Workbook_Open() 
    Call CommandButton1_Click 
End Sub 

https://www.sevenforums.com/tutorials/11949-elevated-program-shortcut-without-uac-prompt-create.html

相關問題