简体   繁体   中英

Runtime error 424 VBA excel

I've had a some success creating a project script that throws up some dialogues to take information, place it on a worksheet (activex box) and then print.

My code runs fine when located in Sheet1 object with the VB editor. However, I want it to run on excel open, so I paste it into the thisworkbook object within workbook_open() , but nothing works.

Can anyone explain to me how I can get this script to run upon excel open, or cease to receive the 424 error when running it from workbook_open() ?

The debugger doesn't like my labelbatch and labelexpiry objects (but only when in thisworkbook ), but it works fine otherwise.

Private Sub Workbook_Open()

ActiveWorkbook.Sheets("sheet1").Activate

'Clears label fields prior to data entry
labelbatch.Caption = ""
LabelExpiry.Caption = ""


'Auto input of batch code into batch field using input text.
BatchNo = InputBox("Enter batch code", " ")
labelbatch.Caption = BatchNo

'Auto input of expiry date into expiry field using input text.
ExpiryDate = InputBox("Enter expiry date", " ")
LabelExpiry.Caption = ExpiryDate

'Show print dialog box
Application.Dialogs(xlDialogPrint).Show

'Close without saving changes
ActiveWorkbook.Close False

  End Sub

Assuming labelbatch and labelExpiry are objects on the worksheet, when the code is moved to ThisWorkbook VBA doesn't know where to look for those objects. Use eg

thisworkbook.worksheets("Sheet1").labelbatch

to refer to them.

When you use a method or property name without all its parents, VBA will either throw an error or will use a default depending on the context. For example, for Cells() , Range() and the like, that default is Application.ActiveSheet . That is generally risky: it's very hard to be sure what the active worksheet will be if you later change your code (or even if a user switches sheets while your code is running). Better to specify which worksheet you want.

This does make references to objects longer, but you can always use With...End With to help readability and save typing.

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