【问题标题】:Auto Sorting with Excel - VBA使用 Excel 自动排序 - VBA
【发布时间】:2014-01-16 23:35:56
【问题描述】:

这是工作时间最长的,但我想我可能做了一些事情把它搞砸了。我已经检查过并重新检查过,它不再对我的数据进行排序。该代码适用于其他工作表,但我无法弄清楚为什么它不能在当前工作表上工作。

它给了我错误“1004”: Range类的排序方法失败

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

'Don't run this code unless a value is last entered in column "H"
  If Not Target.Column = "8" Then Exit Sub

  'Prevents endless loops
    Application.EnableEvents = False



    'Assumptions
    '1.  Data only housed in Columns H
    '2.  The first row contains headings or labels
    '3   Column "H" is used as the sort criteria

      Me.UsedRange.Sort Key1:=Columns("H"), Order1:=xlAscending, _
      Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
      Orientation:=xlTopToBottom

    Application.EnableEvents = True
    On Error Resume Next
    ActiveWorkbook.Save



End Sub

【问题讨论】:

  • 如果我尝试,您的代码可以工作。 H列中的所有数据都有效吗?没有无法排序的混乱计算之类的?
  • 我也是这么说的。我实际上在另一部分中有代码,它工作正常。我在“H”中唯一拥有的是技术名称,例如“joe”或“Phil”。这对我来说没有意义。

标签: vba excel


【解决方案1】:

这似乎对我有用:

Private Sub Worksheet_Change(ByVal Target As Range)
'Don't run this code unless a value is last entered in column "H"
  If Not Target.Column = 8 Then Exit Sub
    MsgBox " "
  'Prevents endless loops
    Application.EnableEvents = False



    'Assumptions
    '1.  Data only housed in Columns H
    '2.  The first row contains headings or labels
    '3   Column "H" is used as the sort criteria

      ActiveSheet.UsedRange.Sort Key1:=Columns("H"), Order1:=xlAscending, _
      Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
      Orientation:=xlTopToBottom

    Application.EnableEvents = True
    ActiveWorkbook.Save

End Sub

确保您在列 H

中有“可排序”数据

【讨论】:

  • 我在 H 中只有一个名字。没有什么是无法排序的。
  • 它也在代码中突出显示了这一部分。 Me.UsedRange.Sort Key1:=Columns("H"), Order1:=xlAscending, _ Header:=xlYes, OrderCustom:=1, MatchCase:=False, _ Orientation:=xlTopToBottom
  • 标题应该在 H1 中。您还需要 H1 下方 的单元格中的一些数据
  • 我拥有所有这些 :( 只是不知道为什么会出错。这里让我把它放在我的保管箱中并分享它。dropbox.com/s/hs357h82d782fq1/Work%20Requests.xlsm
  • 好的,我想我已将其范围缩小到数据透视表。如果我回到标准表,它的排序很好,但由于某种原因,如果它是一个数据透视表,它会导致错误。基本上我需要在每次输入后对数据进行排序。还有其他方法吗?
猜你喜欢
  • 2017-04-23
  • 1970-01-01
  • 2018-09-22
  • 2018-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多