2

我有一个批处理文件,它可以做几件事,最后一步是打开一个 excel 文档并运行其中包含的宏来更新文件的内容。单击按钮即可完美运行宏,但我希望在运行 .bat 文件时完成所有操作。

我知道我可以将宏附加到打开事件中,以便在您打开宏时运行它,但我只希望它在您运行 bat 文件时自动更新,而不是每次打开时。

也许我可以传递一个参数让它知道它是从 .bat 运行的?还是直接用excel命令运行?

like this?
run excel.exe /runMacro "mymacro"   

我在任何地方都找不到我需要的东西,谢谢。

4

2 回答 2

4

是的,基本上最简单的方法是将“mymacro”的内容移动到 ThisWorkBook

Private Sub Workbook_Open()

出于安全考虑,除非您希望无人看管,否则用户可能仍需单击启用宏按钮。如果要将参数传递到打开的工作簿中,则可以通过解析命令行来执行此操作。您可以在 Google 上搜索“excel GetCommandLineW”的代码示例

Private Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
Private Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Private 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

Private Sub Workbook_Open()
    Dim CmdRaw As Long
    Dim CmdLine As String
    CmdRaw = GetCommandLine
    CmdLine = CmdToSTr(CmdRaw)
    ' From here you can parse the CmdLine
    ' ...snip...
于 2012-05-16T15:10:46.687 回答
1

在我的 Excel 2013 版本(15.0.4649.1000 64 位)上,我必须编写以下代码:

#If VBA7 Then
 Private Declare PtrSafe Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As LongPtr
 Private Declare PtrSafe Function lstrlenW Lib "kernel32" (ByVal lpString As LongPtr) As Long
 Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As LongPtr)
#Else
' 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)
#End If


#If VBA7 Then
 Function CmdToSTr(Cmd As LongPtr) As String
#Else
 Function CmdToSTr(Cmd As Long) As String
#End If
 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

Private Sub Workbook_Open()
  Dim CmdRaw As LongPtr
  Dim CmdLine As String
  Dim TabName As String

  CmdRaw = GetCommandLine
  CmdLine = CmdToSTr(CmdRaw)
  MsgBox(CmdLine)
End Sub
于 2014-09-18T21:41:44.550 回答