例如,类 cField 定义如下:
Option Explicit
Public Enum xlsDataType
xdString = 0
xdNumeric = 1
xdDate = 2
End Enum
Public Index As Integer
Public ID As String
Public Value As String
Public DataType As xlsDataType
Private m_Name As String
Public Property Let Name(ByVal data As String)
m_Name = data
DataType = xdString
If InStr(data, "日期") > 0 Then DataType = xdDate
If InStr(data, "数量") > 0 Then DataType = xdNumeric
If InStr(data, "面积") > 0 Then DataType = xdNumeric
If data = "价值" Then DataType = xdNumeric
End Property
Public Property Get Name() As String
Name = m_Name
End Property
集合类 cFields 定义如下:
Option Explicit
Private m_col As New Collection
Public Function Add(ByVal Name As String) As cField
Dim fld As New cField
Static intFldNum As Integer
With fld
intFldNum = intFldNum + 1
.Index = intFldNum
.ID = "F" & Format(intFldNum, "00000")
.Name = Name
m_col.Add fld, .ID
End With
Set Add = fld
End Function
Public Function Count() As Long
Count = m_col.Count
End Function
Public Sub Delete(ByVal Index As Variant)
m_col.Remove Index
End Sub
Public Function Item(ByVal Index As Variant) As cField
Set Item = m_col.Item(Index)
End Function
Public Function NewEnum() As IUnknown
Set NewEnum = m_col.[_NewEnum]
End Function
在例程中:
Function ImportTo()
Dim c As Long
Dim r As Long
c = ActiveSheet.UsedRange.Columns.Count
r = ActiveSheet.UsedRange.Rows.Count
Dim flds As New cFields
Dim i As Long
For i = 1 To c
flds.Add Cells(1, i).Value
Next
Dim f As cField
For Each f In flds
Debug.Print f.Index, f.ID, f.Name, f.DataType, f.Value
Next
End Function
当 For Each 时会报错。
解决办法:
Public Function NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
Attribute NewEnum.VB_MemberFlags = "40"
Set NewEnum = m_col.[_NewEnum]
即手工加入
Attribute NewEnum.VB_UserMemId = -4
隐藏方法
Attribute NewEnum.VB_MemberFlags = "40"
缺省属性
Attribute Item.VB_UserMemId = 0
Public Property Get Item(ByVal Index As Variant) As cField
Attribute Item.VB_UserMemId = 0
Set Item = m_col.Item(Index)
缺省变量
Attribute Value.VB_VarUserMemId = 0
Attribute Value.VB_VarUserMemId = 0