Excel VBA“types不匹配:数组或预期的用户定义的types”
我知道很多人都对这个错误提出了问题,但是根据这些答案,我应该做的都是正确的。
我创build了一个名为Variable
的类来存储有关variables的多个信息。 我有另一个叫做Equipment
类,它存储了这些variables的数组。 这里是Equipment
的相关代码:
Public name As String Private variables() As Variable Public Sub setVariables(vars() As Variable) variables = vars End Sub
我也有一个创buildEquipment
实例的模块。 这里是所有的代码:
Public Sub fillEquipment() 'figure out how many units of equipment there are numUnits = 0 atRow = 1 Do Until Range("A" & atRow).value = "" numUnits = numUnits + 1 atRow = atRow + 1 Loop 'create array for equipment units Dim units() As Equipment ReDim units(0 To numUnits) 'figure out how many variables there are numVars = 0 For Each col In Range("A1:ZZ1") If col.value <> "" Then numVars = numVars + 1 End If Next col 'create an array of equipment one row at a time atRow = 1 Do Until Range("A" & atRow).value = "" 'create and name equipment units(atRow) = New Equipment units(atRow).name = Range("A" & atRow).value 'create an array of vars Dim variables() As Variable ReDim variables(0 To numVars) For atCol = 1 To numVars variables(atCol) = New Variable variables(atCol).name = Cells(1, atCol).value variables(atCol).value = Cells(atRow, atCol).value Next atCol 'add variables to equipment units(atRow).setVariables (variables) atRow = atRow + 1 Loop 'print for testing For atRow = 1 To numUnits Cells(atRow, 1).value = Equipment(atRow).name For atCol = 1 To numCols Cells(atRow, atCol + 1).value = Equipment(atRow).getVariables(atCol) Next atCol Next atRow End Sub
这是我的问题:当我运行该程序时,它给了我units(atRow).setVariables (variables)
variables
units(atRow).setVariables (variables)
的编译器错误“types不匹配:数组或预期的用户定义的types”。
我不明白我做错了什么。 variables
被定义为对象typesVariable
的数组,正是setVariables
所要求的。
谢谢! 我真的很感谢帮助!
你有额外的括号 。 这编译没有错误:
Sub make(numUnits As Long, numVars As Long) Dim units() As Equipment ReDim units(0 To numUnits) Dim atRow As Long, atCol As Long ' <-- new Dim, because of Option Explicit 'create an array of equipment one row at a time atRow = 1 Do Until Range("A" & atRow).value = "" 'create and name equipment units(atRow) = New Equipment units(atRow).name = CStr(Range("A" & CStr(atRow)).value) ' <-- use CStr() anytime you need a string 'create an array of vars Dim variables() As Variable ReDim variables(0 To numVars) For atCol = 1 To numVars variables(atCol) = New Variable variables(atCol).name = Cells(1, atCol).value variables(atCol).value = Cells(atRow, atCol).value Next atCol 'add variables to equipment units(atRow).setVariables variables atRow = atRow + 1 ' ^^^^^^^^^ not (variables) - no parens Loop End Sub
关键问题是括号。 但是,这也为您的variables添加了Dim
语句。 正如@BruceWayne所说,你应该总是使用Option Explicit
。 是的,这是在每个模块和每个class级模块。 否则就是扔掉编译器的debugging帮助。
我其实也在每个模块的顶部使用Option Base 0
,主要是为了提醒自己我正在使用哪个系统:)。
编辑我添加了一些CStr
,它保护你免受怪异的angular落案件。 应该进一步开发这个代码,我会build议使用显式的工作表variables,而不是依靠隐式的ActiveSheet
。 看,例如, 这个答案 。