简体   繁体   中英

Automatically run VBA macro without a message box

I have an Excel macro that I would like to run automatically when the file is opened. The only way I have gotten this to work is by adding a msgbox before calling to my subroutines. However, this requires me to click OK or close the box for the macros to run. I have tried using a timed msgbox sub, but this also does not work.

For some reason, the msgbox pops up before Excel is fully opened, at which point the macro gets stuck here (code for this is below). From here, I tried waiting for the file itself to be opened until it is in write-mode ( Workbook.ReadOnly = false ). This also did not work.

Public Sub msgBoxTimer()
    Const timeout = 2
    Dim objShell As Object
    Set objShell = CreateObject("WScript.Shell")
    objShell.Popup "Measurement will begin shortly", timeout
End Sub
Private Sub Workbook_Open()
    Call msgBoxTimer
    Call init           ' initiate device
    Call updateIndex    ' collect & record measurements
End Sub

I get from your comment that you are probably running other shell commands in init and updateIndex .

What needs to be clear is that when you execute a Shell command via a Shell object in VBA, the default behavior is not to wait for the shell command to complete before running the next line of codes.

If you want Excel to wait for the Shell command to be completed before continuing, you can have a look at the answers to this question .

That being say, if you want Excel to be fully open before running any shell commands, you can use a MsgBox like you originally intended, but it has to be VBA's MsgBox that you would simply call like this:

MsgBox "Measurement will begin shortly"

The VBA thread will wait for the "OK" button to be pressed before continuing the execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM