2010-07-06 100 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

相关问题