【问题标题】:Calling specific module in Vba from batch script从批处理脚本调用 Vba 中的特定模块
【发布时间】:2014-09-09 12:53:00
【问题描述】:

我在 vba 中有三个模块,即 Module1、Module2、Module3 我需要从批处理脚本/命令行调用 Module2 中的 Main() 方法

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

谁能帮帮我? 提前致谢。

【问题讨论】:

  • 到目前为止,您取得了哪些成就?
  • 到目前为止,我可以在使用“Workbook_Open()”函数打开 RelayRec.xlsm 工作表后运行 Module1 Main() 方法。现在我需要从 Workbook_Open() 中删除 Module1 的 Main() 并拥有从批处理脚本本身调用 Module2 的 Main() 方法。

标签: vba excel batch-file


【解决方案1】:

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

关于 SO 的一些链接以及答案

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

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

【讨论】:

  • 谢谢,我必须从宏转到批处理脚本,然后再转到宏,这是我的要求。我尝试使用 Vbs 有帮助,但我不应该使用 Vbs。
【解决方案2】:

一种选择是使用命令行参数来指定调用哪个模块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

【讨论】:

  • 谢谢,我收到“找不到文件”的错误,说 C:\MyFolder\MyWorkbook.xlsm /e /Main2 不存在。
  • 您需要将C:\MyFolder\MyWorkbook.xlsm 替换为您的实际路径和文件名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 2011-06-15
  • 2014-10-14
相关资源
最近更新 更多