简体   繁体   English

Excel按最大到最小字符串对一列进行排序

[英]Excel Sorting one column by Largest to Smallest string

I am trying to sort each of my excel files by one column that has large length text. 我正在尝试按具有大长度文本的一列对每个Excel文件进​​行排序。 This is so the data isn't truncated when imported into SQL using data services job. 这样,使用数据服务作业将数据导入SQL时数据不会被截断。 I realise Excel reads the first 8 or 16 lines and determines the length of field based on that, a lot of my text was getting cut at 255 characters. 我意识到Excel会读取前8或16行,并据此确定字段的长度,我的许多文本都被截断为255个字符。

I tried one file as an experiment and the column was set at 399 varchar, which is the length of the longest string in one of the files. 我尝试使用一个文件作为实验,列设置为399 varchar,这是其中一个文件中最长字符串的长度。 It doesn't matter what size of field I set in DS job mapping, the length of string experienced sets field size. 我在DS作业映射中设置的字段大小与所经历的字符串长度设置的字段大小无关。

I have created a little snippet of VBA to loop through each file and sort by largest to smallest text, it is looping through and is doing something but is not sorting largest to smallest. 我创建了一个VBA的小片段,以遍历每个文件并按最大到最小的文本进行排序,它正在遍历并且正在执行某些操作,但是没有按最大到最小的顺序进行排序。

Not sure if it is empty cells or what that is causing it, however I managed to do this manually for one file - sort largest to smallest - now it never says largest to smallest, only A > Z for some reason. 不知道它是空的还是导致它的原因,但是我设法对一个文件手动执行此操作-大小从大到小排序-现在它从不说从大到小,由于某种原因,只说A>Z。

I have one issue with the code, and that is as I mentioned it is not sorting, and 2) I have one concern about processing multiple files and determining max field length. 我的代码有一个问题,就是正如我提到的那样,这不是排序问题; 2)我对处理多个文件和确定最大字段长度有一个担忧。 I don't know if the DS job will alter the field size if it comes across another file with a larger text length than the last one? 我不知道DS作业是否遇到另一个文本长度比上一个更大的文件而改变了字段大小? I done this with one file, but that doesn't tell me, the only way would be to try and properly sort multiple files, then run the job against each file. 我用一个文件完成了此操作,但这并没有告诉我,唯一的方法是尝试对多个文件进行正确排序,然后针对每个文件运行作业。

Here is the loop wher eI am trying to also do the sort. 这是我正在尝试也进行排序的循环。 I find the column called "sort Me" as an example then apply the sort to it. 我找到名为“ sort Me”的列作为示例,然后对其进行排序。

 For i = 1 To lastcol

        With wb.ActiveSheet
            ColChar = colLtr(i)
            rangestr = ColChar & "1:" & ColChar & "" & MaxRowCount
             If .range(ColChar & 1).Value = "Sort Me" Then
                range(rangestr).Sort key1:=range(rangestr), order1:=xlDescending, Orientation:=xlSortRows, Header:=xlYes
            End If
        End With

    Next i

I have a function that creates the column character from the column number. 我有一个从列号创建列字符的函数。 I loop through each column till I hit the one I want then try and sort. 我遍历每一列,直到找到想要的列,然后尝试进行排序。 the rangestr variable is the range I want to sort. rangestr变量是我要排序的范围。

EDIT: To clarify I want text field longest at top and shortest at bottom, there are, nulls, some sheets have no text. 编辑:澄清一下,我想要文本字段最长在顶部,最短在底部,有,为null,某些工作表没有文本。 Like this: 像这样:

"This is the longest piece of text to be a top"
"This is shorter piece of text"
"This is even shorter"

Mainly would at least like to get the sorting done properly first. 主要是至少希望首先正确完成排序。 Seeking suggestions on how to do that properly. 寻求有关如何正确执行此操作的建议。

Many thanks 非常感谢

Andrew 安德鲁

Excel has powerful built in sorting function that I'd preferably use for both their actual speed and not to reinvent the wheel Excel具有强大的内置排序功能,我最好将其用于实际速度,而不用重新发明轮子

given you need a new (and temporary) field - one with text length in it - I'd also use a "helper" field approach and code as follows: 假设您需要一个新的(临时的)字段-文本长度在其中-我还将使用“ helper”字段方法和代码,如下所示:

Sub SortIt(dataRng As Range, headerStrng As String)
    Dim f As Range, helpRng As Range
    Dim colsOffset As Long

    With dataRng
        Set f = .Rows(1).Find(what:=headerStrng, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False) '<--| look for wanted header column
        If f Is Nothing Then Exit Sub '<--| if no header found, then no job to do!

        Set helpRng = .Resize(, 1).Offset(, .Parent.UsedRange.Columns(.Parent.UsedRange.Columns.Count).Column - .Columns(1).Column + 1) '<--| set a helper range in first column outside worksheet used range and occupying data range same rows
        With helpRng
            colsOffset = .Column - f.Column + 1 '<--| calculate column offset from "header" column to "helper" range
            .FormulaR1C1 = "=len(RC[-" & colsOffset - 1 & "])" '<--| fill "helper" range with corresponding "header" cells number of characters. they will be eventually cleared
        End With
        .Resize(, helpRng.Column - .Columns(1).Column + 1).Sort key1:=helpRng, order1:=xlDescending, Orientation:=xlSortColumns, Header:=xlYes
        helpRng.Clear '<--| clear the "helper" range
    End With
End Sub

to be called by your main sub as follows: 由您的主要子对象调用,如下所示:

Option Explicit

Sub main()
    Dim dataRng As Range, headerStrng As String

    With Worksheets("SortData") '<--| change "SortData" with your actual sheet name
        Set dataRng = .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).Resize(, 10) '<--| change "A1", "A" and '10' to reflect, respectively, your  data actual leftupmost cell, "counter" column (i.e. the one that determines its rows span) and columns number
    End With
    headerStrng = "Sort me" '<--| change "Sort me" with your actual header

    SortIt dataRng, headerStrng
End Sub

Based on a code snippet which I found here 根据我在这里找到的代码段
I edited the code as shown below, just pass in the range you want to sort and set the optional parameter to true if you want to sort by shortest length 我按如下所示编辑了代码,只是传入您要排序的范围,如果要按最短长度排序,则将可选参数设置为true

Sub SortByLength(rangeToSort As Range, Optional shortest As Boolean = False)
    Dim x As Long, y As Long, lLastRow As Long
    Dim tempX As String, tempY As String
    Dim tempArray As Variant

    tempArray = rangeToSort
    'Sort array

    For x = 1 To UBound(tempArray)
        For y = x To UBound(tempArray)
            If shortest = True Then
                If Len(tempArray(y, 1)) < Len(tempArray(x, 1)) Then
                    tempX = tempArray(x, 1)
                    tempY = tempArray(y, 1)
                    tempArray(x, 1) = tempY
                    tempArray(y, 1) = tempX
                End If
            Else
                If Len(tempArray(y, 1)) > Len(tempArray(x, 1)) Then
                    tempX = tempArray(x, 1)
                    tempY = tempArray(y, 1)
                    tempArray(x, 1) = tempY
                    tempArray(y, 1) = tempX
                End If
            End If
        Next y
    Next x
    'Output sorted array
    Range(rangeToSort.Item(1), rangeToSort.Item(UBound(tempArray))) = (tempArray)

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Excel中仅对正数进行排序-从大到小,仅对负数进行排序-在Excel中从小到大 - Sorting only positive numbers – Largest to Smallest & Sorting only negative numbers – Smallest to largest in excel Excel:从“最小到最大”到“AZ”的排序标准不一致 - Excel: Inconsistent sorting criteria from 'Smallest to Largest' to 'A-Z' Excel Display在另一个列公式中的排名从大到小 - Excel Display rank largest to smallest in another column formula 如何使用ColdFusion创建一个Excel文件,该文件的列可以按最大到最小排序,反之亦然? - How to create a Excel file with a ColdFusion which has a column which we can sort by Largest to Smallest or vice versa? 在Excel中基于另一列对一列进行排序 - Sorting one column based on another one in excel 使用 VBA 从最小到最大对数据进行排序的更快方法 - faster method for sorting data smallest to largest using VBA Excel:通过对一个值进行排序来获取一列 - Excel: Obtain a column by sorting anotr one values Excel对具有不同标题的一列进行排序 - Excel Sorting one column with different headers Excel公式可以分组和汇总组中最小和最大的数据 - Excel formulas to group and summarize data with smallest and largest in the group excel通过两个单独的单元格中定义的最小和最大指示数字范围 - excel indicate range of numbers by smallest and largest defined in two individual cells
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM