bat命令打开excel并调用VBA程序

部署运行你感兴趣的模型镜像

面临的需求:

VBA既可以通过人手动触发运行,生成相应的文件;也需要通过命令控制,自动执行VBA生成文件,供其他工具使用。

解决方法:

1. 手动执行VBA只需要在excel中增加绑定宏的按钮即可

2. 通过命令执行是为了供其他系统或者工具使用,解决思路为,其他工具调bat文件,bat文件通过打开excel执行vba

步骤如下:

(1)在VBA中增加workbook的open事件,此事件会在文件打开时触发

(2)写一个bat文件,用于打开excel,同时设置标识,用于标识是bat打开的:

(3)VBA检查是否为cmd命令打开excel,如果是进行后续处理,如果否则不处理,代码如下:

' 32 位系统为
' Declare  Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
' Declare  Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As Long)
' Declare  Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
' 64 位系统为
Private Declare PtrSafe Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As LongPtr
Private Declare PtrSafe Function lstrlenW Lib "kernel32" (ByVal lpString As LongPtr) As LongPtr
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As LongPtr)

Private Sub Workbook_Open()
    
    Dim CmdRaw  As LongPtr
    Dim CmdLine As String
    Dim Msg     As String
 
    CmdRaw = GetCommandLine
    CmdLine = CmdToSTr(CmdRaw)
    Dim paraPos%
    On Error Resume Next ' 这句是必须的,防止非bat打开,下面代码会报错
    paraPos = WorksheetFunction.Search("/batOpen", CmdLine, 1) '检查打开方式
     If paraPos > 0 Then
        MsgBox "bat"
        '===============
         '===============
    Else
        MsgBox "man"
    End If
    
End Sub

' 被调用的子函数 , 用来将命令行参数转换成字符串类型:
Function CmdToSTr(Cmd As LongPtr) As String
    Dim Buffer() As Byte
    Dim StrLen   As LongPtr
    If Cmd Then
        StrLen = lstrlenW(Cmd) * 2
        If StrLen Then
            ReDim Buffer(0 To CInt(StrLen - 1)) As Byte
            CopyMemory Buffer(0), ByVal Cmd, StrLen
            CmdToSTr = Buffer
        End If
    End If
End Function

此时便可以区分是bat打开还是人工打开。bat打开弹窗

人工打开弹窗。需求圆满实现。

参考:https://blog.youkuaiyun.com/richardsa/article/details/6609606

参考:https://www.cnblogs.com/duanyuerui/p/6958631.html

 

 

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值