简体   繁体   English

运行时错误424 VBA excel

[英]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. 我已经成功创建了一个项目脚本,该脚本会引发一些对话以获取信息,将其放在工作表(activex框)上然后打印。

My code runs fine when located in Sheet1 object with the VB editor. 使用VB编辑器在Sheet1对象中找到代码时,我的代码运行正常。 However, I want it to run on excel open, so I paste it into the thisworkbook object within workbook_open() , but nothing works. 但是,我希望它在excel上运行,所以我将它粘贴到workbook_open()thisworkbook对象中,但没有任何效果。

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() ? 任何人都可以向我解释如何让这个脚本在excel打开时运行,或者在从workbook_open()运行时停止接收424错误?

The debugger doesn't like my labelbatch and labelexpiry objects (but only when in thisworkbook ), but it works fine otherwise. 调试器不喜欢我labelbatchlabelexpiry对象(但只有在当thisworkbook ),但另有正常工作。

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. 假设labelbatchlabelExpiry是工作表上的对象,当代码移动到ThisWorkbook时,VBA不知道在哪里查找这些对象。 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. 当您使用不包含其父项的方法或属性名称时,VBA将抛出错误或将使用默认值,具体取决于上下文。 For example, for Cells() , Range() and the like, that default is Application.ActiveSheet . 例如,对于Cells()Range()等,默认为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. 这样可以更长时间地引用对象,但您始终可以使用With...End With来帮助提高可读性并节省输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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