在第一次出现部分字符串后插入行

时间:2015-07-29 19:55:16

标签: excel vba excel-vba

我正在处理一份不断变化的每周报告。列是固定的,但行数会发生变化。我需要格式化它,以便用空行分隔不同的类别。在每个包含要分隔的数据的列上,我有一个代码,用于查找文本字符串的第一个外观,然后在其上方插入两行或三行。

这一直有效,直到我找到由短语" DO NOT BUY"标识的数据部分。 "不要购买"然后跟随(在同一个单元格中) " - 我们之所以不购买"。

由于我仍然希望所有人都不会聚集在一起,我需要的东西只能拉动字符串的第一部分。我试图调整我当前的解决方案以利用左侧功能(查找第一次出现的位置左侧(Columns.AB:AB,10)="不要购买"然后插入行)但我可以'弄清楚如何使Left循环通过整个列而不是一个单元格...

以下是我目前查找和插入行的代码。

Sub InsertBeforeGS()
Dim FindString As String
Dim rng As Range
FindString = "GS"
If Trim(FindString) <> "" Then
    With ActiveSheet.Range("AB:AB")
        Set rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        Lookat:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not rng Is Nothing Then
            Application.GoTo rng, True
            ActiveCell.EntireRow.Insert
ActiveCell.EntireRow.Insert
ActiveCell.EntireRow.Insert
        Else
        End If
    End With
End If
End Sub

1 个答案:

答案 0 :(得分:0)

Sub insert()

Dim lastRow As Long
Dim done As Boolean

'change A to the longest column (most rows)
lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row

For i = 1 To lastRow
    'change the 1 below to the necessary column (ie, use 4 for column D)
    If Left(Cells(i, 1), 10) = "DO NOT BUY" Then
    Rows(i).insert
    done = True
    i = i + 1
    End If
    If done = True Then Exit For
Next

End Sub