VBA自定义类型示例

Option Explicit

Type cwType
    xh As Integer
    xz As String
    cw As String
    sl As Integer
End Type

Sub test()
    Debug.Print GetChaoShiTable(ActiveSheet)
End Sub

Function GetChaoShiTable(sht)

    Dim i, cwArr() As cwType, count, j, tableContent
    
    count = 0
    For i = 3 To sht.UsedRange.Rows.count
        If InStr(sht.Cells(i, "A"), "汇总") = 0 And InStr(sht.Cells(i, "A"), "总计") = 0 And sht.Cells(i, "J") <> 0 Then
            count = count + 1
            ReDim Preserve cwArr(1 To count)
            Dim tempcw As cwType
            With tempcw
                .xz = sht.Cells(i, "A")
                .cw = sht.Cells(i, "B")
                .sl = sht.Cells(i, "J")
            End With
            cwArr(count) = tempcw
        End If
    Next
    
    '排序
    For i = LBound(cwArr) To UBound(cwArr)
        For j = i + 1 To UBound(cwArr)
            If cwArr(i).sl < cwArr(j).sl Then
                Dim temp As cwType
                temp = cwArr(i)
                cwArr(i) = cwArr(j)
                cwArr(j) = temp
            End If
            cwArr(i).xh = i
        Next
    Next
    
    '生成字符串
    tableContent = ""
    count = 0
    For i = LBound(cwArr) To UBound(cwArr)
        count = count + 1
        If count > 10 Then Exit For
        
        tableContent = tableContent & "" & vbCrLf
            
        tableContent = tableContent & vbTab & "" & cwArr(i).xh & "" & vbCrLf
        tableContent = tableContent & vbTab & "" & cwArr(i).xz & "" & vbCrLf
        tableContent = tableContent & vbTab & "" & cwArr(i).cw & "" & vbCrLf
        tableContent = tableContent & vbTab & "" & cwArr(i).sl & "" & vbCrLf
        
        tableContent = tableContent & ""

    Next
        
    GetChaoShiTable = tableContent
End Function

 

你可能感兴趣的:(VBA)