贴个代码留念~- ' 『表格字符串』指定列名、列号排序 by yu2n
-
- ' 指定列名(usr)排序:
- ' sn,usr,pwd
- ' 01,CCC,D00
- ' 02,BBB,E11
- ' 03,AAA,F22
- ' =>
- ' sn,usr,pwd
- ' 03,AAA,F22
- ' 02,BBB,E11
- ' 01,CCC,D00
-
- ' 指定列序号(2)排序:
- ' 01,CCC,D00
- ' 02,BBB,E11
- ' 03,AAA,F22
- ' =>
- ' 03,AAA,F22
- ' 02,BBB,E11
- ' 01,CCC,D00
-
- Demo
- Sub Demo()
- sField = "sn,usr,pwd"
- sContent = "01,CCC,D00" & vbCrLf _
- & "02,BBB,E11" & vbCrLf _
- & "03,AAA,F22"
- ' 指定列名排序
- sTable = sField & vbCrLf & sContent
- WScript.Echo "指定列名(usr)排序:" & vbCrLf & sTable & vbCrLf & "=>" _
- & vbCrLf & SortTableString(sTable, "usr", ",") & vbCrLf
- ' 指定列序号排序
- sTable = sContent
- WScript.Echo "指定列序号(2)排序:" & vbCrLf & sTable & vbCrLf & "=>" _
- & vbCrLf & SortTableString(sTable, 2, ",") & vbCrLf
- End Sub
-
- Function SortTableString(ByVal sTable, ByVal sField, ByVal sFlag)
- ' Format String
- sTable = Trim(sTable)
- If Left(sTable, 2) = vbCrLf Then sTable = Right(sTable, Len(sTable) - 2)
- If Right(sTable, 2) = vbCrLf Then sTable = Left(sTable, Len(sTable) - 2)
- If InStr(sTable, vbCrLf) < 1 Or InStr(sTable, sFlag) < 1 Then Exit Function
- ' init ...
- Dim arr(), arrRows, arrCols, nRowStart
- arrRows = Split(sTable, vbCrLf)
- If UBound(arrRows) = 0 Then Exit Function
- nRowStart = 0
- nRows = UBound(arrRows)
- nCols = UBound(Split(arrRows(0), sFlag))
- ReDim Preserve arr(nCols, nRows)
- For nRow = 0 To nRows
- arrCols = Split(arrRows(nRow), sFlag)
- For nCol = 0 To nCols
- ' Set Table
- arr(nCol, nRow) = arrCols(nCol)
- ' Get nField Index
- If nRow = 0 Then
- If sField = nCol + 1 Then nField = nCol
- If sField = arrCols(nCol) Then nField = nCol: nRowStart = 1
- End If
- Next
- Next
- ' Sort by Field_Index/Field_Name
- Dim i, j, tmp
- For i = nRowStart To nRows
- For j = i + 1 To nRows
- If CStr(arr(nField, i)) > CStr(arr(nField, j)) Then
- tmp = arrRows(i)
- arrRows(i) = arrRows(j)
- arrRows(j) = tmp
- End If
- Next
- Next
- ' Output
- SortTableString = Join(arrRows, vbCrLf)
- End Function
复制代码
|