简体   繁体   English

当工作表A更改Excel VBA时,对工作表B中的数据进行排序

[英]Sort Data in Sheet B when Sheet A Changes Excel VBA

I have three sheets in one workbook in excel. 我在一本Excel工作簿中有三张纸。 I have Sheet A where I paste raw data from another program, Sheet B that takes the data from Sheet A and sorts the first three columns, and Sheet C that uses the sorted data to do calculations. 我有工作表A,在其中粘贴了另一个程序的原始数据,工作表B从工作表A提取了数据,并对前三列进行了排序,工作表C使用了排序后的数据进行计算。

What I would like to do is trigger the sort in Sheet B when I paste data in Sheet A, that way if everything was working you would never have to look at Sheet B. 我想做的就是在我将数据粘贴到工作表A中时触发工作表B中的排序,这样,如果一切正常,您就不必查看工作表B。

I'm not very experienced with Excel VBA but here is what I've gotten from doing some research: 我对Excel VBA的经验不是很丰富,但是这是我做一些研究后得到的:

Private Sub Worksheet_Calculate()

Application.EnableEvents = False
      Range("A1:C314").Sort _
   Key1:=Range("A2"), Order1:=xlDescending, _
     Key2:=Range("B2"), Order2:=xlDescending, _
        Key3:=Range("C2"), Order3:=xlDescending, _
     Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
     Orientation:=xlTopToBottom
     Application.EnableEvents = True

 End Sub

I have this in "Microsoft Excel Objects" in "Sheet B" in the VBA window. 我在VBA窗口的“ Sheet B”中的“ Microsoft Excel对象”中拥有此功能。 The issues I'm having is the macro triggers when I make a change on any sheet, not just Sheet A. What I was trying to accomplish was when I pasted data in Sheet A, the changes in Sheet B would trigger the macro. 我遇到的问题是,在我对任何工作表(而不仅仅是工作表A)进行更改时,宏都会触发。我试图完成的事情是,当我将数据粘贴到工作表A中时,工作表B中的更改会触发宏。

Use a Worksheet_Change event in SheetA instead of the global Worksheet_Calculate. 在SheetA中使用Worksheet_Change事件而不是全局Worksheet_Calculate。

Monitor a cell or a range of cells that will be affected when you paste data, for example to monitor column A for changes and run the rest of the code only when a cell in column A is changed: 监视粘贴数据时将受影响的一个单元格或一系列单元格,例如,监视A列的更改并仅在A列中的单元格发生更改时运行其余代码:

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range("A:A")) Is Nothing Then

' run code to copy the data from SheetA to SheetB
' run code to sort SheetB

End If

End Sub

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

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