vba-type

定义一个type,这个可以用来传递参数

'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
'*
'*  自定义学生对象
'*  做成时间:2020/01/20
'*  做成者: sun
'*  跟新日:
'*  更新者:
'*
'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Type STUDENT_INFO
    '学号
    stuNo As String
    stuName As String
    stuAge As String
    stuSexCode As String
End Type
 
 
'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
'*
'*  定义各种数据类型,处理学生对象情报
'*  做成时间:2020/01/20
'*  做成者: sun
'*  跟新日:
'*  更新者:
'*
'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Sub getStudentInfo()
    
    ' 从Excel的Sheet页中取得情报 例子
    ' Dim sheet As Worksheet
    ' Set sheet = Worksheets("testSheetName")
    ' cellValue = sheet.Cells(2, 3) '2C 单元格 "1001,张三,30,1、1002,李四,31,1、1003,XiaoHong,29,2"
    ' MsgBox cellValue
    
 
    ' 全部学生信息 以字符串形式保存
    Dim allStudentInfo As String
    allStudentInfo = "1001,张三,30,1、1002,李四,31,1、1003,XiaoHong,29,2"
    
    ' 全部学生信息 以数组形式保存【数组使用】
    Dim studentInfoList() As String
    studentInfoList = Split(allStudentInfo, "")
    
    ' 全部学生姓名信息 以key-学号  value-姓名 的Map形式保存
    Dim studentDataList As Object '【数据字典使用-定义】
    Set studentDataList = CreateObject("Scripting.Dictionary")
    
    ' UBound 返回数组的上界 ,★★★不是数组的大小★★★比如数组大小时4,那么上届是3
    For i = 0 To UBound(studentInfoList)
    
        ' 循环设定每个学生的信息
        Dim stuObject As STUDENT_INFO '【自定义数据类型使用】
        stuObject = setStudentInfo(studentInfoList(i))
        
        
        ' 以学号作为Key,存储上面设定好的学生的信息
        ' studentDataList.Add stuObject.stuNo, stuObject  '不好用,无法保存自定义对象
        studentDataList.Add stuObject.stuNo, stuObject.stuName '【数据字典使用 - 设定值】
        
    Next
    
    ' 显示学号是「1002」小明同学的信息
    If studentDataList.exists("1002") Then '【数据字典使用 - 取值】
        MsgBox studentDataList.Item("1002") '【数据字典使用 - 取值】
    End If
        
End Sub
 
'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
'*
'*  设定单个学生对象情报
'*  做成时间:2020/01/20
'*  做成者: sun
'*  跟新日:
'*  更新者:
'*
'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Public Function setStudentInfo(studentInfo As String) As STUDENT_INFO
    ' 单个学生的信息
    Dim infos() As String
    infos = Split(studentInfo, ",")
    
    ' 使用上面定义的学生对象
    Dim stuObject As STUDENT_INFO
    stuObject.stuNo = infos(0)
    stuObject.stuName = infos(1)
    stuObject.stuAge = infos(2)
    stuObject.stuSexCode = infos(3)
    
    ' 设定返回值
    setStudentInfo = stuObject
    
End Function
 

具体使用

 Dim allStudentInfo As String
    allStudentInfo = "1001,张三,30,1、1002,李四,31,1、1003,XiaoHong,29,2"

Dim stuObject As STUDENT_INFO '【自定义数据类型使用】
    stuObject = setStudentInfo(allStudentInfo)
    Debug.Print stuObject.stuNo

 

posted @ 2022-12-06 21:34  vba是最好的语言  阅读(204)  评论(0编辑  收藏  举报