简体   繁体   中英

merge cells based on value of another cell with VBA

I've been working on a project and I'm trying to make things go smoother :)

I have an excel sheet with several columns and as you can see it below, Column C is the importance of the topic(based on information typed in that row) and Column D is whether the information typed is a new information or an update regarding the previous (upper) row. Soo:

if I type "update" on column D, row 3; I want it to automatically merge the cells C2 and C3.

     C      D
1   LOW     new
2   HIGH    new
3          update
4   Low     new
5          update
6          update

I don't know how to write VBA codes but I can mostly understand the codes enough to adopt what I find on internet to what I want to achieve. I have checked so many websites to find whatever I needed but I had no luck so I would really appreciate if you could help me :)

You can try something like this add this Macro in the Current Sheet.

Private Sub Worksheet_Change(ByVal Target As Range)

IF Target.value = "Update" then
     Range("A" & Target.row - 1 & ":A" & Target.row).Merge
End If

End Sub

Try this :

Sub Merge_Priority()
Dim RgToMerge As String


For i = 1 To ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
    RgToMerge = ""
    If LCase(Cells(i, 4)) <> "update" Or (LCase(Cells(i + 1, 4)) <> "new" And Cells(i + 1, 4) <> "") Then
    Else
        RgToMerge = "$C$" & Cells(i, 3).End(xlUp).Row & ":$C$" & i
        With Range(RgToMerge)
            .Merge
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlCenter
        End With
    End If

Next i

End Sub

Do you know how to add a macro on an event?

Go to Visual Studio, select ThisWorkBook on the left and create a macro with this :

Private Sub Worksheet_Change()

And paste the code right above

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