在excel范围内设置优先级的字符串数组排序

时间:2014-09-30 09:20:43

标签: vba excel-vba excel

我有两个范围A1:A5,其值为a,b,c,d,e和B1:B5,其中B3为1,B5为2。

我使用下面的代码来获取字符串数组中的范围值。

Option Base 1

Sub test()

    Dim s(5) As String
    For i = 1 To 5
        s(i) = Range("A" & i)
    Next

End Sub

现在我想基于B列值(Priorty)对字符串数组进行排序(如果有的话)。

预期结果。

s(1)="c"
s(2)="e"
s(3)="a"
s(4)="b"
s(5)="d"

如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

Option Base 1

Public Sub test()

    Dim rng As Range
    Dim shtSourceSheet As Worksheet
    Dim shtTempSheet As Worksheet
    Dim s(5) As String


    Set shtSourceSheet = ThisWorkbook.Worksheets("your sheet")
    Set shtTempSheet = ThisWorkbook.Worksheets.Add()

    Set rng = shtSourceSheet.Range("A1", "B5")
    rng.Copy shtTempSheet.Cells(1, 1)
    Set rng = shtTempSheet.Range("A1", "B5")
    rng.Sort shtTempSheet.Range("B1", "B5")

    For i = 1 To 5
        s(i) = shtTempSheet.Cells(i, 1)
    Next i

    Application.DisplayAlerts = False
    shtTempSheet.Delete
    Application.DisplayAlerts = True

    For i = 1 To 5
        Debug.Print s(i)
    Next


End Sub

答案 1 :(得分:1)

Option Base 1
Sub t()
Dim myarr() As String

With ActiveSheet

    For i = 1 To 5
        ReDim Preserve myarr(i)
        myarr(i) = .Range("b" & i) & .Range("a" & i)
    Next i


For i = 1 To UBound(myarr)
    For j = i + 1 To UBound(myarr)
        If myarr(i) > myarr(j) Then
            temp = myarr(i)
            myarr(i) = myarr(j)
            myarr(j) = temp
        End If
    Next j
Next i

For i = 1 To UBound(myarr)
    For j = 1 To 5
        myarr(i) = WorksheetFunction.Substitute(myarr(i), .Range("b" & j).Value, "")
    Next j
Next i

        .Range("c1:c5") = WorksheetFunction.Transpose(myarr)
 End With

 End Sub