1

我在两个单独的数组中有两个输入数据 Year 和 Name 。我需要先对两个数组值进行排序,我需要按时间顺序(年份)对其进行排序,然后如果年份信息重复,它将按字母顺序对数组进行排序。

至于我完成了年份和名称的排序。使用Wordbasic.sortarray命令

输入:(排序前)

SDF 1997
ELS 1986
PJK 1983
WKL 1995
EFD 1986

输出:(排序后)

PJK 1983
EFD 1986
ELS 1986
WKL 1995
SDF 1997

如果我用word打印它,它会像这样打印:

PJK 1983, ELS 1986, EFD 1986, WKL 1995, SDF 1997.

这是我打印数据的代码。有人可以调查一下并指导我在哪里犯了错误吗?

WordBasic.sortarray SortyearArray()

代码

Dim I As Integer
Dim J As Integer
Dim K As Integer
Dim N As Integer
Dim Counter As Integer
COUNTER1 = 1

i1 = 1
J1 = 5

For I = 0 To UBound(SortyearArray())
    Counter = 1
    For J = I + 1 To UBound(SortyearArray())
        If SortyearArray(I) = SortyearArray(J) Then
            Counter = Counter + 1
            MsgBox (Counter)
        End If
        COUNTER1 = Counter + COUNTER1
    Next J
    If Counter = 1 Then
        For N = i1 To J1
            If SortyearArray(I) = Year(N) Then
                Selection.TypeText Text:="(" & AuthorName(N) & Year(N) & ")"
            End If
        Next N
    End If
Next I
4

1 回答 1

2

输入

SDF 1997
ELS 1986
PJK 1983
WKL 1995
EFD 1986

核心功能:

    Public Function QuickSort(ByRef array2check() As String, min As Long, max As Long) As Boolean
Dim lo As Long, hi As Long
Dim lo0 As Long, hi0 As Long
Dim midPos As String

    lo = min: hi = max
    lo0 = lo: hi0 = hi
    midPos = array2check((lo0 + hi0) / 2)
    DoEvents
    While (lo <= hi)
        While ((lo < hi0) And (array2check(lo) < midPos))
            lo = lo + 1
        Wend
        While ((hi > lo0) And (array2check(hi) > midPos))
            hi = hi - 1
        Wend
        If lo <= hi Then
            Call swap(array2check, lo, hi)
            lo = lo + 1
            hi = hi - 1
        End If
    DoEvents
    Wend

    If lo0 < hi Then Call QuickSort(array2check, lo0, hi)
    If lo < hi0 Then Call QuickSort(array2check, lo, hi0)

    QuickSort = True

End Function

Private Sub swap(arr() As String, idx1 As Long, idx2 As Long)
Dim tmp As String
    tmp = arr(idx1)
    arr(idx1) = arr(idx2)
    arr(idx2) = tmp
End Sub

样品测试仪

Public Sub sample_test()
    Dim test_arr() As String
    test_arr = Split("SDF 1997" & vbCrLf & "ELS 1986" & vbCrLf & "PJK 1983" & vbCrLf & "WKL 1995" & vbCrLf & "EFD 1986", vbCrLf)
    If QuickSort(test_arr, LBound(test_arr), UBound(test_arr)) = True Then
        'Debug.Print Join(test_arr, vbCrLf)
        MsgBox Join(test_arr, vbCrLf)
    End If
End Sub

结果

EFD 1986
ELS 1986
PJK 1983
SDF 1997
WKL 1995

希望这可以帮助。

于 2012-06-13T10:00:56.660 回答