VBA代码在特定文本值下面插入行

问题描述:

我需要在“总计”文本值下插入一行。我需要通过代码遍历所有活动的工作表。它只需要查看A列。我是VBA的新手,所以代码越简单越好。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的单元格。如果找不到,则会出现一个消息框,如果发现在它上面插入了新的一行。

+0

当代码单中的所有单元格都为空时,您的代码将返回运行时错误91。为避免这种情况,您可以在LastLine开始之前插入'On Error Resume Next' – Tehscript

+0

代码更新:) – PedroMVM