简体   繁体   中英

Auto sorting and Merging of the cells using vba in excel

I have autosorted two of my rows using VBA in excel.

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next

    If Not Intersect(Target, Range("C:D")) Is Nothing Then
        Range("C3").Sort Key1:=Range("C4"), _
          Order1:=xlAscending, _
          Key2:=Range("D4"), _
          Order2:=xlAscending, _
          Header:=xlYes, _
          OrderCustom:=2, MatchCase:=False, _
          Orientation:=xlTopToBottom
    End If
End Sub

I have auto sorted column C and D in ascending order.

But when i merge 2 cells in Column J (ie J53 and J54) the auto sorting does not work for the Column C and D or the entire sheet we can say.

I want to merge the cells in Column J as well as make Column C and D auto sort using VBA.

NB: similarly i want to sort to 2 cells in Column K as well.

Sorting does not work with merged cells. Except when all merged cells are the same size.

I highly recommend not to use On Error Resume Next without proper error handling. It just makes you blind to any errors but they still occur, you will just never know because the message is suppressed.

That is also why you didn't see the error message telling you exactly this! Remove On Error Resume Next and you will see the error message!

Solution
You can unmerge the cells to sort them, or use a 3ʳᵈ party tool like Kutools: How To Sort Data With Merged Cells In Excel?

Note that this is not the only case why merged cells are evil. Therefore I recommend not to use merged cells at all.

我将取消合并单元格,然后进行排序,然后再次合并...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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