故事还在继续......我之前的两个问题是关于成员函数
fReadData
和fReadData2
Public Function fReadData(alue As Range) As Double
pOne = alue.Cells(1)
fReadData = pOne
End Function
Public Function fReadData2(alue As Range) As ClassOne
Set fReadData2 = New ClassOne
pOne = alue.Cells(1)
fReadData2.One = pOne
End Function
现在两个版本都可以工作(列表都可以),但现在我想知道为什么下面的
fReadData3
总是给出与 fReadData
或 fReadData2
相同的结果? 与 fReadData2
相比,唯一的区别是附加变量 foo
。
Public Function fReadData3(alue As Range) As ClassOne
Set fReadData3 = New ClassOne
Dim foo As Double
foo = alue.Cells(1)
fReadData3.One = foo
End Function
一些测试:
函数
Test
已在 Test3
之前运行。
Test3
给出与 Test
相同的值
当
Test2
先于 Test3
运行时,Test3
给出与 Test2
相同的结果
班级
ClassOne
如下
'ClassOne
Option Explicit
Private pOne As Double
Private Sub Class_Initialize()
End Sub
Private Sub Class_Terminate()
End Sub
Public Property Get One() As Double
One = pOne
End Property
Public Property Let One(lOne As Double)
pOne = lOne
End Property
Public Function fReadData(alue As Range) As Double
pOne = alue.Cells(1)
fReadData = pOne
End Function
Public Function fReadData2(alue As Range) As ClassOne
Set fReadData2 = New ClassOne
pOne = alue.Cells(1)
fReadData2.One = pOne
End Function
Public Function fReadData3(alue As Range) As ClassOne
Set fReadData3 = New ClassOne
Dim foo As Double
foo = alue.Cells(1)
fReadData3.One = foo
End Function
工作表测试如下
' main module
Option Explicit
Dim oOne As New ClassOne
Function Test(alue As Range) As Double
oOne.fReadData alue
Test = oOne.One
End Function
Function Test2(alue As Range) As Double
oOne.fReadData2 alue
Test2 = oOne.One
End Function
Function Test3(alue As Range) As Double
oOne.fReadData3 alue
Test3 = oOne.One
End Function
哦。
Public Function fReadData3(alue As Range) As ClassOne
Set fReadData3 = New ClassOne
Dim foo As Double
foo = alue.Cells(1)
fReadData3.One = foo
End Function
Function Test3(alue As Range) As Double
oOne.fReadData3 alue
Test3 = oOne.One
End Function
fReadData3 创建新对象并将所需的值分配给该对象,但在 Test3 中你想从另一个对象获取该值。
正确代码:
Function Test3(alue As Range) As Double
dim tmp
set tmp = oOne.fReadData3(alue)
Test3 = tmp.One
End Function