2010-10-05 31 views
0

我想要做的是編寫一個VB宏,它將掃描整個列(列F)灼熱爲「Year Total:」,然後插入一個整行在它下面。在excel中查找某個值並在其下面添加整行使用Vbscript

我有這樣的:

子Macro2() ' ' Macro2宏 ' ' 快捷鍵:Ctrl +一

Dim C As Variant 
Dim FirstRow As Integer 

With Worksheets(1).Range("F1:F4000") 
    Set C = .Find("Year Total:", LookIn:=xlValues) 
    If Not C Is Nothing Then 
     FirstRow = C.Row 
     Do 
      C.Offset(1, 0).Insert Shift:=xlDown 
      Set C = .FindNext(C) 
     Loop While Not C Is Nothing And C.Row <> FirstRow 
    End If 


End With 

結束子

然而,它只會增加細胞,而不是整行。

我還想添加到代碼中,因爲它還在同一列中搜索「Grand Total:」,並在其下添加三行。我只是要寫兩個腳本,但是如果我可以將它們混合在一起,那就太好了。

回答

1

好的,在這裏你去,我只是測試它,這就是訣竅。我確信有一個更乾淨的方法可以做到這一點,但這聽起來像是在一個快速ñ'骯髒的解決方案之後,所以這希望能爲你工作。 :)

' Get last row 
intLastRow = ActiveSheet.Range("F" & Rows.Count).End(xlUp).Row 

' Loop till last row 
intRow = 0 
For Each strColFValue In ActiveSheet.Range("F1:F" & intLastRow).Value 
    intRow = intRow + 1 

    ' If found year, insert row below 
    If InStr(UCase(strColFValue), "YEAR TOTAL:") > 0 Then 
     Range("F" & intRow + 1).Select 
     Selection.EntireRow.Insert 
     intRow = intRow + 1 
    End If 

    ' If found grand total, insert 3 rows below 
    If InStr(UCase(strColFValue), "GRAND TOTAL:") > 0 Then 
     Range("F" & intRow + 1).Select 
     Selection.EntireRow.Insert 
     Selection.EntireRow.Insert 
     Selection.EntireRow.Insert 
     intRow = intRow + 3 
    End If 

Next 
相關問題