【问题标题】:How can I sort the new data in every new sheet by the first column?如何按第一列对每个新工作表中的新数据进行排序?
【发布时间】:2021-10-07 17:22:42
【问题描述】:

在使用前几张表中的数据制作了几张新表之后,我希望宏按字母顺序对新表上的数据进行排序。问题似乎在于这些新数据的大小并不总是相同的。

Dim New_Products As Range
Dim New_Sheets As Worksheet
[...]
For Each New_Sheets In Worksheets
    If New_Sheets.Name <> "Sheet1" And New_Sheets.Name <> "Sheet2" Then
        New_Sheets.Activate
        Set New_Products = Range("A1", Range("A1").End(xlToRight).End(xlDown))
        New_Sheets.Sort.SortFields.Clear
        New_Sheets.Sort.SortFields.Add2 Key:=Range("A2", Range("A2").End(xlDown)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With New_Sheets.Sort
            .SetRange Range("A1", Cells(Range("A1").End(xlDown).Row, Range("A1").End(xlToRight).Column))
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End If
Next New_Sheets

当我尝试运行宏时,我得到:

Run-time error '1004'
The sort reference is not valid. Make sure that it's within the data you want to sort, and the first Sort By box isn't the same or blank.

【问题讨论】:

  • 应该SetRangeNewProducts
  • 不要使用.Activate 而不是使用New_Sheets 引用所有您的RangeCells 对象,例如New_Sheets.RangeNew_Sheets.Cells 来制作您的代码可靠。
  • @Nathan_Sav 它应该是,但它之前没有工作,这就是我删除它的原因。我应该重新添加它吗?

标签: excel vba sorting foreach runtime-error


【解决方案1】:

试试这个代码:

Sub SortWSs()
    Dim New_Products As Range, New_Sheets As Worksheet
    For Each New_Sheets In Worksheets
        Select Case New_Sheets.Name
            Case "Sheet1", "Sheet2"
            Case Else
                Set New_Products = New_Sheets.Range("A1").CurrentRegion
                With New_Sheets.Sort
                    .SortFields.Clear
                    .SortFields.Add2 Key:=New_Products.Columns(2), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
                    .SetRange New_Products
                    .Header = xlYes
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With
        End Select
    Next New_Sheets
End Sub

【讨论】:

  • 宏不再给出错误,这很好,但第一列没有按字母顺序排列。我不确定宏中的 Columns(2) 是做什么的,但我可以告诉你,这张表中的列数要高得多。列的数量实际上是来自不同宏的变量,这就是我使用 End(xlToRight) 的原因。
  • 1) .Columns(2) 用作排序列(将其更改为您想要的任何内容) 2) .CurrentRegion 获取整个连续范围,因此通常不需要使用 End(xlToRight)在这种情况下
  • ...但如果您的数据由空白列和行分隔,则 .CurrentRegion 应替换为 .End(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
相关资源
最近更新 更多