【发布时间】:2020-03-05 10:37:18
【问题描述】:
我目前正在开发一个 VBA 项目。我只有 VBA(没有 OOP,只有函数和子程序)和 C# 的基础知识。
今天我正在尝试创建我的第一个类,但我遇到了一个错误。
这是类的样子:
'CLASS Disponent
Private Sub Class_Initialize()
m_dispocode = 1
m_name = Unknown
m_suppliers
m_materials
SetID
End Sub
Private m_materials As New ArrayList
Private m_suppliers As New ArrayList
Private m_name As String
Private m_dispocode
Private m_id As String
Property Get Id() As Integer
Id = m_id
End Property
Property Get Suppliers(value As Integer) As String
If value >= 0 And value < m_suppliers.Count Then
Suppliers = m_suppliers(value)
Else
Err.Raise ERROR_INVALID_INDEXING, "ReadWorksheet", "The indexer used in the arraw is out of bounds"
End If
End Property
Property Let Suppliers(supp As String)
m_suppliers.Add supp
End Property
Property Get Dispocode() As Integer
Dispocode = m_dispocode
End Property
Property Let Dispocode(dispcode As Integer)
If dispcode > 0 And dispcode < 1000 Then
m_dispocode = dispcode
Else
Err.Raise ERROR_INVALID_DISPOCODE, "ReadWorksheet", "The value must be between 1 (incl) and 999 (incl)"
End If
End Property
Property Get name() As String
name = m_name
End Property
Property Let name(name As String)
If Len(name) > 3 Then
m_name = name
Else
Err.Raise ERROR_INVALID_NAME, "ReadWorksheet", "The name must be at least 3 letters long"
End Property
Property Get Materials(indexof As Integer) As ArrayList
If indexof >= 0 And indexof < m_suppliers.Count Then
Materials = m_materials(indexof)
Else
Err.Raise ERROR_INVALID_INDEXING, "ReadWorksheet", "The indexer used in the arraw is out of bounds"
End If
End Property
Property Let Materials(materialnum As String)
m_materials.Add materialnum
End Property
Public Sub SetID()
m_id = m_name & m_dispocode
End Sub
这就是我尝试在普通模块的 SUB 中创建对象的方式:
Sub GenerateDisponents()
Dim last_row As Long
last_row = Sheets("Disponents").Cells(Rows.Count, 1).End(xlUp).Row
Dim Dispos As New Collection
For i = 1 To last_row
Dim temp As New Disponent
Dim name As String
name = Sheets("Disponents").Range("B" & i).value
Dim code As Integer
code = Sheets("Disponents").Range("A" & i).value
temp.name = name
temp.Dispocode = code
Dispos.Add temp
MsgBox ("DONE")
End Sub
当我尝试运行 GenerateDisponents sub 时,我在 Let Materials 属性上收到以下错误: “同一属性的属性过程定义不一致,或属性过程有可选参数、ParamArray 或无效的 Set 最终参数。”
对于早期绑定,我使用以下参考:C:\Windows\Microsoft.NET\Framework\v4.0.30319.\mscorlib.dll。
你们知道我的代码为什么不起作用吗?
我确信它充满了错误,因为这是我第一次尝试在 VBA 中使用类。
提前感谢您的帮助!
【问题讨论】:
-
为什么不在声明类的实例后立即调用
Class_Initialize()? -
我怀疑你的
Err.Raise程序。暂时把它们拿出来,看看代码没有它们能不能运行。 -
@Variatus 我试过了。不幸的是没有帮助。
-
我会继续这样,取出部分 Property Let 程序,直到没有任何东西可以冒犯。我会删除很多代码,以确保确实是您正在检查的一个过程导致错误,以防万一有多个。