简体   繁体   中英

insert cell next to a cell that contains a certain value

I would like to get some help with a sheet that I'm trying to create.

My issue

I would like to make a macro, which inserts a cell next to a cell with a certain value. My sheet looks somewhat like this:

Invoice       14-12-2017   USD     400,00  
Discount                   USD     125,65  
Creditmemo    14-12-2017   USD     205,60  
Invoice       16-12-2017   USD     906,75  
Invoice       19-12,2017   USD     855,00  
Discount                   USD     105,80  

The issue is that I want to insert a cell to the right of cells containing the word "Discount", since the data is not aligned in the right columns, whenever a discount cell appears.

What I have so far

    Cells.Find(What:="Discount", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate

    ActiveCell.Offset(0, 1).Insert Shift:=xlShiftToRight

Goal

I would like the For Each string to allow me to use what I have found out so far, and reuse it until it reaches the bottom of my data. When it reaches the bottom, it should stop the find process, and continue whatever I might have below this function of the macro. Is it possible for me to get VBA to do what I ask of it? Please let me know.

If you want to loop through the cells and insert to right then:

Sub Button1_Click()
    Dim LstRw As Long
    Dim Rng As Range, c As Range

    LstRw = Cells(Rows.Count, "A").End(xlUp).Row
    Set Rng = Range("A1:A" & LstRw)
    For Each c In Rng.Cells
        If LCase(c) = "discount" Then
            c.Offset(, 1).Insert Shift:=xlToRight
        End If
    Next c
End Sub

If you want to insert when there is a blank cell then you could use special cells.

Sub InsertOnBlank()

    Columns("B:B").SpecialCells(xlCellTypeBlanks).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub

If your data is in Sheet1, then the following should do what you expect:

Sub foo()
LastRow = Sheets("Sheet1").Cells(Sheets("Sheet1").Rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
    If Sheets("Sheet1").Cells(i, 1).Value = "Discount" Then Sheets("Sheet1").Cells(i, 2).Insert Shift:=xlToRight
Next i
End Sub

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