2017-04-26 124 views

回答

0

下面的代碼應該做你需要的東西:

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