VBA代码在特定文本值下面插入行
答
下面的代码应该做你需要的东西:
Sub InsertLineAfterGrandTotal()
Dim WS As Integer
Dim LastLine As Long
Dim LookingArea As Range
Dim FoundCell As Range
For WS = 1 To Application.Sheets.Count
Sheets(WS).Activate
On Error Resume Next ' To avoid error when all cells are empty
LastLine = Sheets(WS).Cells.Find("*", LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Row
Set LookingArea = Sheets(WS).Range(Cells(1, 1), Cells(LastLine, 1))
Set FoundCell = LookingArea.Find("Grand Total", LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByColumns)
If FoundCell Is Nothing Then
MsgBox "Grand Total not found in sheet " & Sheets(WS).Name & _
". Press Ok to continue", vbExclamation + vbOKOnly, "Not found"
Else
FoundCell.Offset(1, 0).EntireRow.Insert
End If
Next WS
End Sub
解释:
1)For
循环使其变为整个工作簿中的所有工作表。
2)LastLine
,如名称所示,获取活动工作表的最后一行。 3)LookingArea
是搜索字符串Grand Total
的范围。
4)FoundCell
将指向找到Grand Total
的单元格。如果找不到,则会出现一个消息框,如果发现在它上面插入了新的一行。
当代码单中的所有单元格都为空时,您的代码将返回运行时错误91。为避免这种情况,您可以在LastLine开始之前插入'On Error Resume Next' – Tehscript
代码更新:) – PedroMVM