您好,我一直在尝试这个网站给我的不同解决方案,但我不能让我的代码运行。我有一个用户定义的Type()和一个Sub()和一个函数。像这样:
Type Base
UT As String
N_Inic As Integer
N_Fin As Integer
Largo As Integer
End Type
Sub Test()
Dim A() As Base
A = Base()
End Sub
Function Base() As Base
Sheets("ARISTAS").Select
ActiveSheet.Cells(2, 1).Select
j = 2
b = 0
Set UT_Range = Range(ActiveCell, Cells(Rows.Count,_ Selection.Column).End(xlUp))
Total_1 = UT_Range.Count
Dim Base_UT() As Base
ReDim Base_UT(Total_1)
While Sheets("ARISTAS").Cells(j, 1).Value
Base_UT(b).UT = Sheets("ARISTAS").Cells(j, 1).Value
Base_UT(b).N_Inic = Sheets("ARISTAS").Cells(j, 2).Value
Base_UT(b).N_Fin = Sheets("ARISTAS").Cells(j, 3).Value
Base_UT(b).Largo = Sheets("ARISTAS").Cells(j, 9).Value '**
b = b + 1
j = j + 1
Wend
Base = Base_UT
End Function
当我运行我的子时,它表示无法分配矩阵并突出显示" A"
有人知道为什么吗?
非常感谢你
答案 0 :(得分:0)
您已将A()
声明为Base
类型的数组,并且您还包含一个名为Base
的函数。从维护和可读性的角度来看,这是一个坏主意,我强烈建议为您的功能指定一个不同的名称。
那就是说,使用简单的例子我可以通过调整函数签名来返回数组来实现这个目的:
Sub Test()
Dim a() As Base
a = GetBase()
End Sub
Function GetBase() As Base()
Dim Total_1 As Long
Dim b As Long
b = 0
Total_1 = 0
Dim Base_UT() As Base
ReDim Base_UT(Total_1)
Base_UT(b).UT = "string"
Base_UT(b).N_Inic = 1
Base_UT(b).N_Fin = 2
Base_UT(b).Largo = 3
GetBase = Base_UT
End Function
答案 1 :(得分:0)
而不是:
Function Base() As Base
使用:
Function Base() As Base()
但代码中存在其他可能的错误,以下代码应该有助于避免
Function Base1() As Base()
Dim b As Long, Total_1 As Long
Dim UT_Range As Range, cell As Range
With sheets("ARISTAS")
Set UT_Range = .Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp))
Total_1 = UT_Range.Count - 1
ReDim Base_UT(Total_1) As Base
For Each cell In UT_Range.SpecialCells(XlCellType.xlCellTypeConstants)
Base_UT(b).UT = cell.Value
Base_UT(b).N_Inic = cell.Offset(, 1).Value
Base_UT(b).N_Fin = cell.Offset(, 2).Value
Base_UT(b).Largo = cell.Offset(, 8).Value '**
b = b + 1
Next cell
ReDim Preserve Base_UT(b - 1)
End With
Base1 = Base_UT
End Function
如您所见,我还更改了函数名称以使其与UDT名称
不匹配答案 2 :(得分:0)
以下是基于您的问题的一个非常简单的示例:
Type Base
UT As String
N_Inic As Integer
N_Fin As Integer
Largo As Integer
End Type
Sub MAIN()
Dim alpha As Base
alpha = whatever()
MsgBox alpha.UT & alpha.N_Inic & alpha.N_Fin & alpha.Largo
End Sub
Public Function whatever() As Base
Dim poiuyt As Base
poiuyt.UT = "hello"
poiuyt.N_Inic = 11
poiuyt.N_Fin = 17
poiuyt.Largo = 19
whatever = poiuyt
End Function
它在函数中使用类型Base
的内部变量,并将其传回: