简体   繁体   English

Excel-如果特定单元格发生更改,则按列自动排序

[英]Excel - Automatically sort by a column if a specific cell changes

I have a report in Excel (2010) which is refreshable. 我在Excel(2010)中有一个可刷新的报告。 Cell S3 contains a unique 8 digit number which will be different each time the report is refreshed. 单元格S3包含一个唯一的8位数字,每次刷新报告时该数字都会不同。 Rows 1 and 2 are just headers and other info; 第1和2行只是标题和其他信息; the actual data is returned on row 3 downwards 实际数据从第3行向下返回

What I'd like to be able to do is have the report automatically sort any data from row 3 downwards, AZ by column F (and of course all the adjacent data along with their respective row, if that makes sense) if the contents of cell S3 is ever changed. 我想做的是让报告自动将第3行中的所有数据按F列从AZ向下排序(如果有意义的话,所有相邻数据以及它们各自的行,如果有意义的话)。单元格S3曾经改变过。

Is this possible in VBA? 在VBA中可以吗?

Many thanks. 非常感谢。

You can use Worksheet_Change event like this: 您可以像这样使用Worksheet_Change事件:

Private Sub Worksheet_Change(ByVal Target As Excel.Range) 
    If Target.Column = 19 And Target.Row = 3 Then 
      Dim lastrow As Long
      lastrow = Cells(Rows.Count, 2).End(xlUp).Row
      Range("A3:F" & lastrow).Sort key1:=Range("F3:F" & lastrow), _
           order1:=xlAscending, Header:=xlNo
    End If 
End Sub

For sorting see here . 有关排序,请参见此处 However: 然而:

This event does not occur when cells change during a recalculation. 当单元在重新计算期间发生更改时,不会发生此事件。 Use the Calculate event to trap a sheet recalculation. 使用Calculate事件可以捕获工作表重新计算。

If you need to check value changes caused by recalculation, you will have to store old value of S3 cell in a variable and compare this old value with a new value. 如果需要检查由重新计算引起的值更改,则必须将S3单元格的旧值存储在变量中,并将此旧值与新值进行比较。 See this answer . 看到这个答案

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM