尝试从另一个模块使用类方法时,VBA错误424

我在excel 2013的类模块中有一个名为autoCRUD的类。从另一个模块(一个普通的模块)我尝试从这个类中调用一个方法,并得到“Object required”exception。

这里的方法是:

Public Function CreateCRUDView(TipoCRUD As String) 'TipoCRUD pode ser C (Create), R (Read), U (Update), D (Delete) Dim myForm As Object Dim NewFrame As MSForms.Frame Dim NewButton As MSForms.CommandButton Dim NewListBox As MSForms.ListBox Dim NewLabel As MSForms.Label Dim X As Integer Dim Line As Integer Dim t As Integer Dim arrLeg() As Variant arrLeg = legenda 'This is to stop screen flashing while creating form Application.VBE.MainWindow.Visible = False Set myForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm) 'Create the User Form With myForm .Properties("Caption") = "New Form" .Properties("Width") = 300 .Properties("Height") = 270 End With 'Criar labels t = 10 For Each lbl In arrLeg Set NewLabel = myForm.Designer.Controls.Add("Forms.label.1") With NewLabel .name = "lbl_" + Replace(CStr(lbl.Value), " ", "") .t = (10 + t) .Left = 10 .Font.Size = 8 End With t = t + 10 Next 'Create CommandButton Create Set NewButton = myForm.Designer.Controls.Add("Forms.commandbutton.1") With NewButton .name = "cmd_1" If UCase(TipoCRUD) = "C" Then .Caption = "Salvar" ElseIf UCase(TipoCRUD) = "U" Then .Caption = "Alterar" End If .Accelerator = "M" .Top = Top + 10 .Left = 200 .Width = 66 .Height = 20 .Font.Size = 8 .Font.name = "Tahoma" .BackStyle = fmBackStyleOpaque End With Top = Top + 10 End Function 

另一个调用该方法的模块的代码是:

 Public Sub Main() Dim ac As autoCrud Set ac = New autoCrud ac.CreateCRUDView ("c") End Sub 

我不明白,为什么我得到这个错误?

这里是“legenda”的代码:

 Public Property Get sht() As Worksheet Const shtName As String = "Teste1" Set sht = ActiveWorkbook.Worksheets(shtName) End Property Public Property Get legenda() As Range Const linha As Integer = 3 Const colunaI As Integer = 2 Dim colunaF As Integer Dim i As Integer i = colunaI Do While sht.Cells(linha, i).Value <> "" i = i + 1 Loop colunaF = (i - 1) Set legenda = sht.Range(Cells(linha, colunaI), Cells(linha, colunaF)) End Property 

lbl.Value应该是一个string值,即标签的名称。 它来自表格头部的电子表格,teh legenda()只select那个头部,arrLeg把legenda作为一个范围,并把它转换成一个数组。 编辑:

显然,错误发生在这样的一行: .name = "lbl_" + Replace(CStr(lbl.Value), " ", "")如你所见,我试图从string中取出空格确保它是一个string,但没有一个工作。

编辑2:

我实际上只是使用一个类来组织和可重用性的目的。 我将这些属性和其他方法在'createCRUDView'方法中使用,然后这个方法创build一个CRUD视图,也就是创build一个“创build”,“读取”(因为它是excel不使用),“更新或“删除”数据条目,它基本上是为你创build的任何表格dynamic创build表单

VBA错误424是对象所需的错误。 所以我现在很确定在CStr(lbl.Value)中的lbl不是一个对象。 随着你的代码legenda是一个Range但之后

 Dim arrLeg() As Variant arrLeg = legenda 

arrLeg将是一个变体数组。 这个数组不包含对象。 你可以用这个来debugging

 For Each lbl In arrLeg ... MsgBox TypeName(lbl) ... Next 

所以你应该使用CStr(lbl)

 Set legenda = sht.Range(Cells(linha, colunaI), Cells(linha, colunaF)) 

只会在“Teste1”工作表是ActiveSheet的情况下工作,因为Cells(linha, colunaI)没有明确分配给工作表,所以ActiveSheet将被假设。

 Set legenda = sht.Range(sht.Cells(linha, colunaI), sht.Cells(linha, colunaF)) 

会更好。