VBA类成员函数和类定义问题

问题描述 投票:0回答:1

我正在尝试制作 Excel VBA 类成员函数

fReadData
,它从 Excel 电子表格返回一些值并使用类定义
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


Property Get fReadData(alue As Range) As Double

    Dim oFreadData As New ClassOne
    
    oFreadData.One = alue.Columns(1)
    fReadData = oFreadData.One
    
End Property

该类的测试使用如下

' main module

Option Explicit

Dim oOne As New ClassOne

Function Test(alue As Range) As Double

oOne.fReadData (alue)
Test = oOne.One

End Function

函数

Test
应从电子表格中读取单元格 (B1) 并将答案放入单元格 (B3)。 现在的结果是“公式中使用的值的数据类型错误”。

在此输入图片描述

如果我省略成员函数

fReadData
代码可以工作

' main module

Option Explicit


Dim oOne As New ClassOne



Function Test(alue As Range) As Double

'oOne.fReadData (alue)

oOne.One = alue.Columns(1)
Test = oOne.One

End Function

结果值得期待

在此输入图片描述

excel vba class member-functions
1个回答
0
投票

在此声明中

oFreadData.One = alue.Columns(1)

值数组分配给 Double 类型的变量,这是错误的。

alue.Columns(1)
返回“alue”第一列的所有单元格。

你可以这样表达:

oFreadData.One = alue.Cells(1)

alue
第一个单元格的值分配给
One

© www.soinside.com 2019 - 2024. All rights reserved.