具有集合对象引用的VBA Excel错误424

所以我正在创build一个收集数据的用户表单,并使用这些数据来生成报告。 有很多的问题,用户被问到。 具体来说,这个表单上的testing有几个相同的问题。 众多的存在使得用户可以在表格上input关于众多testing的信息。 我对VBA excel相对比较陌生,而且我无法弄清楚如何为所有的重复性问题块创build一个类模块。 因此,我已经提出了8.每个块中的问题用不同的数字命名,例如:TestType1_ComboBox,TestType2_ComboBox等等。

是的,我意识到这是非常低效的,但是我设置类模块时遇到了很多麻烦。

我想能够引用所有的X_ComboBoxes例如,所以我可以用一个循环很容易地AddItem的所有。 我做了一个集合,所以我可以引用所有的TestType_ComboBoxes效率。 我打算为8个问题块中的所有控件做这种types的参考。

问题:当我尝试引用集合中的对象时,出现424对象引用错误。

''' create collections: Public ttComboBox As Collection Public ttAmountBlocked As Collection Public ttgcFileName As Collection Public ttsoiDate As Collection Public ttsoiTime As Collection Public ttReportUse As Collection Sub ReportGenerationTool() ' set variables: '...other code ' make organList an array list Set organList = CreateObject("System.Collections.ArrayList") '...more code ' set collections and add respective controls Set ttComboBox = New Collection With ttComboBox .Add (Report_Form.TestType1_ComboBox) .Add (Report_Form.TestType2_ComboBox) .Add (Report_Form.TestType3_ComboBox) .Add (Report_Form.TestType4_ComboBox) .Add (Report_Form.TestType5_ComboBox) .Add (Report_Form.TestType6_ComboBox) .Add (Report_Form.TestType7_ComboBox) .Add (Report_Form.TestType8_ComboBox) End With ttComboBox.Item(1).AddItem "Test" '**^THIS IS WHERE I GET THE 424 ERROR**' Set ttAmountBlocked = New Collection '...similar set up as above Set ttgcFileName = New Collection '...similar set up as above Set ttsoiDate = New Collection '...similar set up as above Set ttsoiTime = New Collection '...similar set up as above Set ttReportUse = New Collection '...similar set up as above ' initialize report form Call ReportForm_Initialize ' show report form Report_Form.Show End Sub 

通常,我有这样的代码行: ttComboBox.Item(1).AddItem "Test" (和其他人喜欢它)在ReportForm_Initialize()子。 基本上我想要这样:Report_Form.TestType1_ComboBox.AddItem“testing”与此:ttComboBox(1).AddItem“testing”如果不与集合,我如何得到这个function?

该错误意味着一个对象是预期的,但没有提供,所以你的集合实际上不包含对象(如表单控件combobox),但其他的东西。

我用一个testing场景证实了这一点,截图如下

如果你看看Locals窗口中的集合,你会看到它保存string值,而不是表单控件/combobox对象! 由于string值属性没有.Add方法,因此会引发424错误。

在这里输入图像说明

为什么集合包含string而不是ComboBox?

在VBA中,括号通常会对expression式进行评估

有时候这没关系。 例如, ("hello")计算方式与"hello"相同,但对于像表单控件这样的对象,括号会计算为该对象的默认属性(可能是.Value属性)。

如何解决?

很简单,只需从.Add语句中删除括号即可。

 With ttComboBox .Add Report_Form.TestType1_ComboBox .Add Report_Form.TestType2_ComboBox .Add ...etc. 

或者你可以变得更有趣,改变整个街区:

 With ttComboBox .Add (Report_Form.TestType1_ComboBox) .Add (Report_Form.TestType2_ComboBox) .Add (Report_Form.TestType3_ComboBox) .Add (Report_Form.TestType4_ComboBox) .Add (Report_Form.TestType5_ComboBox) .Add (Report_Form.TestType6_ComboBox) .Add (Report_Form.TestType7_ComboBox) .Add (Report_Form.TestType8_ComboBox) End With 

对此(假设这些是您的窗体上唯一的combobox):

 Dim cbox as Object For each cbox in Report_Form.Controls If TypeName(cbox) = "ComboBox" Then ttComboBox.Add cBox End If Next