2012-04-20 34 views
2

在一个Excel宏,我已经定义了一个函数想返回记录,像这样VBA为什么我必须将类变量变暗为变体而不是其类型?

Function GetCommissionDataRecordset(doctorCode As String) As ADODB.Recordset 
    Set GetCommissionDataRecordset = New ADODB.Recordset 
    . 
    . ' setup the connection and SQL string... 
    . 
    GetCommissionDataRecordset.Open strSQL 
end function 

,我试图调用函数像这样

sub tester() 
    'Dim oRecSet As ADODB.Recordset ' this doesn't work, needs to be a variant 
    Dim oRecSet As Variant 
    Set oRecSet = GetCommissionDataRecordset("GC") 
    'Copy Data to Excel' 

    ActiveSheet.Range("a1").CopyFromRecordset (oRecSet) 
end sub 

如果tester子过程我定义oRecSet as ADODB.Recordset ,在执行CopyFromRecordset时出现运行时错误。

错误消失时,我定义oRecSetVariant

运行时错误是430 Class does not support Automation or does not support expected interface

发生错误时,手表告诉我的oRecSet类型是Recordset/Recordset

当我使用的变体的方法,观察告诉我的oRecSet类型为Variant/Object/Recordset

检查对象的属性在观察似乎表明对我来说没有区别。

这是怎么回事?

回答

7

的CopyFromRecordSet需要一个变量参数。如您(意外?)因为发送的()左右oRecSet按值记录,类型匹配似乎是相当严格的,导致错误。

如果您更改您的来电:

ActiveSheet.Range("a1").CopyFromRecordset oRecSet 

时oRecSet是一个记录它会工作,但你将不会被强制按值参数传递。实际上,函数声明没有指定如果参数BYVAL或为ByRef,但人们不会想到一个“复制记录”的方法来改变它的内容。

3

你没有,你只需要删除括号

ActiveSheet.Range("a1").CopyFromRecordset oRecSet 
相关问题