VBA类模块--添加类的函数(2)
为CTable类添加一个Create方法,代码就变成下面这个样子了
CTable 类模块:
1 Option Explicit 2 3 '==================================== 4 '名称: CTable 5 '功能: 描述一个Excel表格区域 6 '==================================== 7 8 9 '类的属性 10 Public strName As String ' 表名 11 Public strAddress As String ' 地址 12 Public rngStart As Range ' 开始单元格 13 Public rngEnd As Range ' 结束单元格 14 Public iColumns As String ' 列数 15 16 '类的方法 17 ' 18 '==================================== 19 '名称: Create 20 '功能: 把CTable的对象实现出来 21 '参数:strName:表名 22 ' strWhere:表要创建的位置 23 ' astrWhat:列名数组 24 '返回值:无 25 '==================================== 26 Public Function Create(strName As String, strWhere As String, astrWhat As Variant) 27 Dim i, col 28 If Not IsArray(astrWhat) Then Exit Function 29 strName = strName 30 strAddress = strWhere 31 Set rngStart = Range(strWhere) 32 rngStart.Value = strName 33 34 For Each col In astrWhat 35 rngStart.Offset(1, i).Value = col 36 i = i + 1 37 Next 38 Set rngEnd = rngStart.Offset(1, i - 1) 39 rngStart.Offset(0, 1).Value = rngEnd.Address 40 41 iColumns = i 42 rngStart.Offset(0, 2).Value = iColumns 43 End Function
Create 就是类的一个方法。
Data普通模块:
1 Sub 创建学生表2() 2 Dim clsStudentTable As New CTable ' 声明并创建一个对象 3 Dim astrColumnNames As Variant 4 5 astrColumnNames = Array("id", "Name", "Gender", "StuID", "Class") 6 clsStudentTable.Create "学生表", "Sheet2!$A$1", astrColumnNames '类方法的使用: 对象名.方法名 7 End Sub