对(键,字符串)对动态集进行排序VB6

时间:2018-09-20 10:51:24

标签: vb6

任何人都可以告诉我使用VB6对由键设置的动态(键,字符串)进行排序的最佳方法是什么。 我试图使用VBA.collections和2D数组。但是他们似乎有一个很大的解决方法来进行排序。 我还尝试过stackoverflow question.

中提到的MSComctlLib.ListView
Dim lvSelectedStyles As MSComctlLib.ListView
Dim listItem As MSComctlLib.listItem
'Some code here
lvSelectedStyles.ListItems.Add Key:=CStr(lngCount) Text:=objParagraph.Key

但是,此项添加给出一个错误,提示“对象或未设置块变量”。如果我可以解决此问题,则可以按列对列表视图进行排序,然后继续前进。

任何人都可以让我知道克服该问题的方法,或者如果您有其他方法可以做到这一点,请告诉我。

谢谢。

1 个答案:

答案 0 :(得分:3)

尝试使用Recordset对象进行这种排序

Option Explicit

Private Function pvSortImpl(vData As Variant, _
            ByVal lKeyType As Long, _
            ByVal lKeySize As Long, _
            ByVal lValueType As Long, _
            ByVal lValueSize As Long) As Variant
    Const adFldIsNullable As Long = 32
    Dim rs              As Object
    Dim vElem           As Variant
    Dim vFields         As Variant
    Dim vRetVal         As Variant
    Dim lIdx            As Long
    Dim oFldKey         As Object
    Dim oFldValue       As Object

    Set rs = CreateObject("ADODB.Recordset")
    rs.Fields.Append "Key", lKeyType, lKeySize, adFldIsNullable
    rs.Fields.Append "Value", lValueType, lValueSize, adFldIsNullable
    rs.Open
    vFields = Array(0, 1)
    For Each vElem In vData
        rs.AddNew vFields, vElem
    Next
    If rs.RecordCount = 0 Then
        vRetVal = Array()
    Else
        rs.Sort = "Key"
        ReDim vRetVal(0 To rs.RecordCount - 1) As Variant
        Set oFldKey = rs.Fields("Key")
        Set oFldValue = rs.Fields("Value")
        rs.MoveFirst
        Do While Not rs.EOF
            vRetVal(lIdx) = Array(oFldKey.Value, oFldValue.Value)
            lIdx = lIdx + 1
            rs.MoveNext
        Loop
    End If
    pvSortImpl = vRetVal
End Function

Public Function SortNumeric(vData As Variant) As Variant
    Const adDouble      As Long = 5
    Const adVarWChar    As Long = 202

    SortNumeric = pvSortImpl(vData, adDouble, 0, adVarWChar, 1000)
End Function

Public Function SortStrings(vData As Variant) As Variant
    Const adVarWChar    As Long = 202

    SortStrings = pvSortImpl(vData, adVarWChar, 202, adVarWChar, 1000)
End Function

Private Sub Form_Load()
    Dim vResult         As Variant

    vResult = SortStrings(Array(Array("bbb", "test"), Array("aaa", Now)))
    Debug.Print Join(vResult(0), "=>")
    Debug.Print Join(vResult(1), "=>")
    vResult = SortNumeric(Array(Array("33", "test"), Array("2.2", Now), Array("22", "Proba")))
    Debug.Print Join(vResult(0), "=>")
    Debug.Print Join(vResult(1), "=>")
    Debug.Print Join(vResult(2), "=>")
End Sub

这将在立即窗口中打印

aaa=>9/21/2018 11:50:19 AM
bbb=>test
2.2=>9/21/2018 11:50:19 AM
22=>Proba
33=>test