如果I + 2包含某些文本,则VBA插入行

时间:2019-02-04 18:44:06

标签: excel vba

所以我有一个Excel表格,可以包含5-1500行中的任意行。大多数行具有:1)标题行,2)患者信息,3)空白行。然后重复。有些行包含1)标题行,2)患者信息,3)其他患者信息,4)空白行。如果第3行中有信息,我需要在第2&3行之间插入一行。这有意义吗? 示例:
-------- A --------------------- b ----------------- c- ------------------ d --------
1 -----帐号#--------病人姓名------博士姓名------服务日期
2 ------ 123456 -------米老鼠-----唐老鸭-------- 1/4/19
3 ----------(((((((((((((此行的所有为空白)))))))))))))))))))))))))))) ))----------

或者可能是这样:
-------- A --------------------- b ------------------- -c ------------------- d ------
1 -----帐号#--------病人姓名--------博士姓名------服务日期
2 ------ 123456 -------米老鼠-----唐老鸭-------- 1/4/19
3 ------ 123456 -------米老鼠-----唐老鸭-------- 1/4/19
4 ----------(((((((((((((此行的所有为空白)))))))))))))))))))))))))))) ))----------

然后,相同的格式会在整个工作表中重复,当然会有不同的信息。我需要的是,如果第3行有任何信息,则在拖线2和3之间插入一行,但是如果第3行为空白,则跳至下一组。

这是我到目前为止的代码,但是无论如何,它每隔一行添加一行。

Sub Macro()
Dim lastRow As Integer
lastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.count).Row
Dim I As Long
For I = 6 To lastRow
If Cells(I + 2, 9).Text <> "" Then
Rows(I + 1).EntireRow.Insert Shift:=xlDown
lastRow=lastRow+1

End If
Next I
End Sub

2 个答案:

答案 0 :(得分:0)

正如@BruceWayne在评论中所述,在插入或删除行,列或单元格时,向后迭代很有帮助。 Step循环的For-Next参数允许您定义要迭代的方式。默认为Step 1。因此,与其从I = 6 to lastRow开始迭代,要么尝试

Dim lastRow As Long
Dim i As Long
lastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
For i = lastRow To 6 Step -1
    If Cells(i - 1, 9).Text <> "" And Cells(i, 9).Text <> "" Then
        Rows(i).EntireRow.Insert Shift:=xlDown
    End If
Next i

如果当前单元格及其上方的单元格中都包含数据,则会在您当前的迭代中插入一行。

值得注意的是,如果要迭代到第1行,上面的If语句将引发错误,但您永远不需要。

编辑:

如果您只需要在患者信息和其他患者信息之间添加一行,则需要找到一条可连续识别的数据作为条件添加到If语句中。

答案 1 :(得分:0)

尝试一下。

自定义变量以符合您的需求

Sub InsertRows()

    ' Define object variables
    Dim rangeEval As Range
    Dim currentCell As Range

    ' Define other variables
    Dim sheetName As String
    Dim rowCounter As Integer

    ' >>>> Customize this
    sheetName = "Sheet1"

    ' Initialize the used range in column A ' Change the number in .Columns(1) to use another column
    Set rangeEval = ThisWorkbook.Worksheets(sheetName).UsedRange.Columns(1)


    ' Loop through each cell in range
    For Each currentCell In rangeEval.Cells

        ' We use this counter to check if we are every third row
        rowCounter = rowCounter + 1

        ' If this is the third row and there is something in the cell, insert one row
        If rowCounter Mod 3 = 0 And currentCell.Value <> vbNullString Then

            currentCell.EntireRow.Insert

        ' Reset the counter if there is nothing in the cell
        ElseIf currentCell.Value = vbNullString Then

            rowCounter = 0

        End If

    Next currentCell


End Sub