从批处理脚本调用Vba中的特定模块

时间:2014-07-18 11:34:04

标签: vba excel-vba batch-file excel

我在vba中有三个模块,即Module1,Module2,Module3 我需要从Batch脚本/命令行

中调用Module2中的Main()方法

我使用了命令 启动excel.exe / e" C:\ temp \ RelayRec.xlsm" 打开excel后,将执行Module1 Main()方法。 现在我想更具体地调用从Module1 Main()方法中删除链接后从命令行调用Module2 Main()方法。

有人可以帮帮我吗? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

使用VBS脚本打开excel实例,然后您可以加载文件并运行您感兴趣的宏/函数。这应该为您提供所需的所有控件。

关于SO的一些链接和答案

https://stackoverflow.com/a/2056066/2448686

https://stackoverflow.com/a/10894162/2448686

答案 1 :(得分:0)

一个选项是使用命令行参数指定要调用的模块Main方法。我找到了一些代码来检索命令行here

创建一个新模块并添加以下代码:

Option Base 0
Option Explicit

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)

Function CmdToSTr(Cmd As Long) As String
  Dim Buffer() As Byte
  Dim StrLen As Long

  If Cmd Then
    StrLen = lstrlenW(Cmd) * 2
    If StrLen Then
      ReDim Buffer(0 To (StrLen - 1)) As Byte
      CopyMemory Buffer(0), ByVal Cmd, StrLen
      CmdToSTr = Buffer
    End If
  End If
End Function

Workbook_Open方法中,检索命令行并检查参数:

Private Sub Workbook_Open()
  Dim CmdRaw As Long
  Dim CmdLine As String

  CmdRaw = GetCommandLine
  CmdLine = CmdToSTr(CmdRaw)

  If InStr(CmdLine, "Main2") > 0 Then
    Module2.Main
  Else
    Module1.Main
  End If
End Sub

在批处理文件中,像这样运行Excel:

EXCEL.EXE C:\MyFolder\MyWorkbook.xlsm /e /Main2