我有一个Excel VBA宏,需要在从批处理文件访问文件时运行,但不是每次打开文件时都要运行(因此不使用打开文件事件)。有没有办法从命令行或批处理文件中运行宏?我不熟悉这样的命令。
假设您的环境是Windows NT。
我有一个Excel VBA宏,需要在从批处理文件访问文件时运行,但不是每次打开文件时都要运行(因此不使用打开文件事件)。有没有办法从命令行或批处理文件中运行宏?我不熟悉这样的命令。
假设您的环境是Windows NT。
你可以使用VBScript文件启动Excel,打开工作簿并运行宏。
将下面的代码复制到记事本中。
更新“MyWorkbook.xls”和“MyMacro”参数。
将其保存为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", 0, True)
xlApp.Run "MyMacro"
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
运行宏的关键代码是:
xlApp.Run "MyMacro"
xlApp.Visible = True
,否则您将看不到Excel或任何可能出现的对话框。 - Rachel HettingerSet xlApp = CreateObject("Excel.Application")
在我的系统上无法工作。您能否指导我如何使其正常工作? - Mubeen Shahid最简单的方法是:
1)从批处理文件启动Excel,打开包含宏的工作簿:
EXCEL.EXE /e "c:\YourWorkbook.xls"
2) 在工作簿的 Workbook_Open
事件中调用你的宏,例如:
Private Sub Workbook_Open()
Call MyMacro1 ' Call your macro
ActiveWorkbook.Save ' Save the current workbook, bypassing the prompt
Application.Quit ' Quit Excel
End Sub
现在这将会把控制权返回给你的批处理文件去执行其他操作。
EXCEL.EXE
和工作簿):Set MacroName=MyMacro
"C:\Program Files\Microsoft Office\Office15\EXCEL.EXE" "C:\MyWorkbook.xlsm"
将以下代码放入Excel VBA的ThisWorkBook对象中:
Private Sub Workbook_Open()
Dim strMacroName As String
strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
If strMacroName <> "" Then Run strMacroName
End Sub
将您的代码放入Excel VBA模块中,如下所示:
Sub MyMacro()
MsgBox "MyMacro is running..."
End Sub
运行批处理文件并获取结果:
如果您不打算运行任何宏,请在批处理中将值为空Set MacroName=
。
Private Declare Function GetEnvVar Lib "kernel32" Alias "GetEnvironmentVariableA" _
(ByVal lpName As String, ByVal lpBuffer As String, ByVal nSize As Long) As Long
Function GetEnvironmentVariable(var As String) As String
Dim numChars As Long
GetEnvironmentVariable = String(255, " ")
numChars = GetEnvVar(var, GetEnvironmentVariable, 255)
End Function
Private Sub Workbook_Open()
If GetEnvironmentVariable("InBatch") = "TRUE" Then
Debug.Print "Batch"
Else
Debug.Print "Normal"
End If
End Sub
根据需要添加活动代码。在批处理文件中,使用以下命令:
set InBatch=TRUE
我一直在Workbook_Open()函数中测试打开的工作簿数量。如果是1,则说明该工作簿是通过命令行打开的(或者用户关闭了所有工作簿,然后打开了这个)。
If Workbooks.Count = 1 Then
' execute the macro or call another procedure - I always do the latter
PublishReport
ThisWorkbook.Save
Application.Quit
End If
不要直接比较字符串(VB不会认为它们相等,因为GetEnvironmentVariable返回长度为255的字符串),请写成这样:
Private Sub Workbook_Open()
If InStr(1, GetEnvironmentVariable("InBatch"), "TRUE", vbTextCompare) Then
Debug.Print "Batch"
Call Macro
Else
Debug.Print "Normal"
End If
End Sub
xlam
加载项中,因此我想打开一个工作簿,然后运行存储在另外地方的宏。由于这需要一个VBS脚本,我想使其“便携”,以便可以通过传递参数使用它。这是最终脚本,它需要3个参数。
我这样测试它:
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"
runmacro.vbs:
Set args = Wscript.Arguments
ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
macrowb= WScript.Arguments.Item(2)
End If
LaunchMacro
Sub LaunchMacro()
Dim xl
Dim xlBook
Set xl = CreateObject("Excel.application")
Set xlBook = xl.Workbooks.Open(ws, 0, True)
If wscript.arguments.count > 2 Then
Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
End If
'xl.Application.Visible = True ' Show Excel Window
xl.Application.run macro
'xl.DisplayAlerts = False ' suppress prompts and alert messages while a macro is running
'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
'xl.activewindow.close
xl.Quit
End Sub
@ Robert: 我尝试使用相对路径调整了您的代码,并创建了一个批处理文件来运行VBS。
VBS可以启动并关闭,但没有启动宏……不知道问题出在哪里?
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFilePath = objFSO.GetAbsolutePathName(".")
Set xlBook = xlApp.Workbooks.Open(strFilePath, "Excels\CLIENTES.xlsb") , 0, True)
xlApp.Run "open_form"
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
然后我创建了一个vbs文件来启动这个宏(使用相对路径有些棘手):
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
最终我编写了一个批处理文件来执行VBS脚本...
@echo off
pushd %~dp0
cscript Add_Client.vbs
Userform_QueryClose
中包含了“设置回可见”的内容。Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ThisWorkbook.Close SaveChanges:=True
Application.Visible = True
Application.Quit
End Sub
void Main()
{
var oExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
try{
var WB = oExcelApp.ActiveWorkbook;
var WS = (Worksheet)WB.ActiveSheet;
((string)((Range)WS.Cells[1,1]).Value).Dump("Cell Value"); //cel A1 val
oExcelApp.Run("test_macro_name").Dump("macro");
}
finally{
if(oExcelApp != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcelApp);
oExcelApp = null;
}
}