所以我有一个可以从5-1500线路的任何地方一个Excel工作表。大多数线具有:1)标题行,2)患者信息,3)空白行。然后重复。一些线具有1)标题行,2)患者信息,3)附加的患者信息,4)空白行。我需要插入的行2和3之间的线路是否有行3确实信息这有意义吗?例: --------阿--------------------- b ----------------- C- ------------------ d -------- 1 ----- ACCT#--------服务的病人的名字------博士的名字------日期 2 ------ 123456 -------米老鼠-----唐老鸭-------- 19年1月4日 3 ----------((((((((((((((所有这行的是空白))))))))))))))))))) ))----------
或者,它可能是这样的: --------阿--------------------- b ------------------- -光盘 - - - 1 ----- ACCT#--------服务的患者姓名--------博士的名字------日期 2 ------ 123456 -------米老鼠-----唐老鸭-------- 19年1月4日 3 ------ 123456 -------米老鼠-----唐老鸭-------- 19年1月4日 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
作为@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
语句的条件。
试试这个。
自定义变量,以满足您的需求
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