简体   繁体   中英

Insert extra row in a loop if a specific requirement is met

Quite new to programming in general and especially in VBA. I am trying to build a code that adds a blank row if a specefic requirement is met in a cell ie if a cell in coloumn B is blank. My data input varies in size so cannot define a specific range I suppose.

The data looks like this:

在此处输入图像描述

So far my code looks like this but this it only adds blank rows in the top as soon as column b is empty.

For i = 1 To k
  If out.Range("B16").Cells(i, 1) = "" Then
   out.Rows(i).Insert shift:=xlShiftUp
End If
Next i 

What my code basically does is that it adds a bunch of lines up top atm so it moves the table 6-7 rows down.

Assuming the table data like this:
在此处输入图像描述

Need to insert entire row if a cell in column B is blank.
So the table become something like this:

在此处输入图像描述

The code:

Sub test123()
Set x = Range("B16")
Do Until x.Offset(1, 0).End(xlToRight).Value = "" And x.Offset(1, 0).End(xlToLeft).Value = ""
If x.Value = "" Then
If x.End(xlToRight).Value <> "" Or x.End(xlToLeft).Value <> "" Then
x.EntireRow.Insert
'x.Offset(-1, 0).Interior.Color = vbGreen
End If
End If
Set x = x.Offset(1, 0)
Loop
End Sub

The condition to insert entire row are:
1. if there is a blank cell in column B
2. to the end-left or to the end-right of this blank cell has value.
The code will stop if to the end-left and to the end-right of this blank cell has no value

That's if I'm not mistaken to get what you mean.

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