VBA Collection带来excel工作表

时间:2016-02-01 10:36:43

标签: excel-vba vba excel

我正在努力将数据从集合粘贴到工作表中。 我创建了一个类模块,并使用SQL查询填充了该集合 最后一步是将我在集合中的数据粘贴到电子表格中,当我运行代码时,我会收到一条错误消息' 13'类型不匹配

Class Modules Company 
Public Street As String 
Public City As String 
Public Country As String 

Dim cmpCollection As Collection
Dim cmp As Company


Do While Not rs.EOF 
cmp.Street = rs!Street 
cmp.City = rs!City cmp.Country = rs!Country 
rs.MoveNext Loop 

'Where rs is a recordset with the result of the SQL query

For Each cmp In cmpCollection
Sheets("Sheet1").Cells("A1") = cmpCollection.Item(cmp)
Next cmp

你有什么建议吗?

Class Modules 
Company Public Street As String 
Public City As String 
Public Country As String 
Do While Not rs.EOF cmp.Street = rs!Street
 cmp.City = rs!City cmp.Country = rs!Country rs.Move
Next Loop 

其中rs是具有SQL查询结果的记录集

由于

1 个答案:

答案 0 :(得分:0)

首先,在类中使用getter和setter并使用私有变量更清晰。然后,您可以选择仅公开您想要公开的属性(可能与您的示例无关,因为所有属性都是)。

公司类模块:

'Variables stored in class:
Private p_Street as string
Private p_City as string
Private p_Country as string

'Getters to expose the stored variables to the outside world.
Public Property Get Street() as String
    Street = p_Street
End Property
Public Property Get City() as String
    City = p_City
End Property
Public Property Get Country() as String
    Country = p_Country
End Property

'Setters (Let in VBA) to populate:
Public Property Let Street(value as String)
    p_Street = value
End Property
Public Property Let City(value as String) 
    p_City = value
End Property
Public Property Let Country(value as String)
    p_Country = value
End Property

现在您拥有公司类,您可以在常规模块中创建公司对象的集合,如下所示(现在不需要将集合本身​​包装在另一个类中):

Public CompanyCollection as Collection 'Global variable, so it can be used / altered later on


Public Sub PopulateCollection()
Dim rs as ADODB.RecordSet 'I assume it's ADODB?
Dim cmp as Company
Set CompanyCollection = new Collection

'Get your recordset here

Do While rs.EOF = False
    Set cmp = New Company
    cmp.Street = rs.Fields.Item("Street")
    cmp.City = rs.Fields.Item("City")
    cmp.Country = rs.Fields.Item("Country")
    CompanyCollection.Add cmp
    rs.MoveNext
Loop

End Sub

现在,您可以遍历Collection并将其写入Sheet 1中的多个行,如下所示:

Sub WriteCollectionToSheet()
Dim cmp as Company
Dim i as integer 'Indexer to make sure the next row will be used for the next Company Object.

i = 1 
For each cmp in CompanyCollection 
    With ThisWorkbook.Worksheets(1)
        .Cells(i, 1).value = cmp.Street   
        .Cells(i, 2).value = cmp.City
        .Cells(i, 3).value = cmp.Country 
    End With
    i = i + 1
Next cmp


End Sub

但是,如果您在其他地方不需要此集合,则从RecordSet直接写入工作簿会更有效。

总结:上面让您将RecordSet转换为存储在集合中的自定义公司对象(通过PopulateCollection)。由于CompanyCollection存储为全局变量,您可以稍后访问它并使用WriteCollectionToSheet将存储在其中的项目写入工作表。

但是,根据场景,我会反过来建议不要直接从记录集填充单元格,或者,如果有默认的非参数化查询,只需使用Excel的本机连接,只需执行ThisWorkbook.RefreshAll