删除文本之间的行

时间:2013-11-07 19:24:48

标签: excel-vba delete-row vba excel

我有一个很长的复杂宏,我不断添加文本以改进。现在它是完美的,除了最后一个宠物项目。基本上有一个报告,我们转储到excel和宏格式化报告,但有时报告是多个页面,有两个标题。我想删除一个标题,但保留另一个标题。显然,标题位于不同的文本之间,具体取决于分页的位置。我能够编写代码来查找某些内容并删除行,但是删除了我要保留的页面1标题。这些是财务报表,标题文本如下:

报告ID:DC_COMPINC 格式ID:VARSUM 重新预测Bud:MFC09 样式ID:@

但是也有一堆空白行。我不确定是否可以这样做,当然手动删除文本并不是什么大问题我只是想尽可能地自动化。据我所知,总共需要删除10行,前4个是上面的文本,下面是6个空白行。

2 个答案:

答案 0 :(得分:1)

如果标题始终以相同的特定字符开头,则可以遍历行,查找标题文本的任何辅助实例,并删除所需的行集。在下面的代码中,您需要指定CommonHeaderText字符串以及报告中的第一个单元格。

Sub HeaderRemover()

' dim the variables
Dim FirstCell As Range
Dim CommonHeaderText, DeletionRowString As String
Dim HeaderInstances As Integer

' modify to grab the right header and start in the right place
CommonHeaderText = "Test Header"
Set FirstCell = Range("A1")

' initialize the counter
HeaderInstances = 0

' loop through the rows, removing extra header lines
For i = 0 To FirstCell.CurrentRegion.Rows.Count
    ' check if header text starts the specific cell
    If CommonHeaderText = Left(FirstCell.Offset(i), Len(CommonHeaderText)) Then
        HeaderInstances = HeaderInstances + 1
        ' remove the desired rows if this is this isn't the first instance of the header text
        If HeaderInstances > 1 Then
            ' remove 10 sequential rows, starting 3 rows before the header row
            DeletionRowString = i - 2 & ":" & i + 7
            Rows(DeletionRowString).Delete Shift:=xlUp
        End If
    End If
Next i

End Sub

注意,如果有空行,则FirstCell.CurrentRegion.Rows.Count将无法正常工作。你可以做一些聪明的事情,或者只是硬编码一个足够大的整数,因为这不是计算密集型的。

答案 1 :(得分:0)

在运行灭菌代码之前,只需将初始标头预先读入缓冲区以保留它,以忽略其余的页眉。如果您知道标题是10行,那么您可以预先缓冲前十行。即使标题记录具有可变长度,您也只需要预先缓冲,直到到达您标识为数据而不是标题行的第一行。所以基本上(伪代码):

    currLine = readLine(inputFile)

    do while not isData(currLine) {          
    \\ isData(string) would compare the string to criteria you identify as a data record
        fileBuffer = fileBuffer + currLine   \\ Add the header line to the string buffer for the file
        currLine = readLine(inputFile)  \\ Read the next line
    }

   \\ At this point you've segregated the one header that you want 
   \\ so read the rest of the file

    do while not endOfFile(inputFile) {
        if isData(currLine) {
        \\ Add the line to the buffer only if it appears to be a data line
           fileBuffer = fileBuffer + currLine
        }
        currLine = readLine(inputFile) \\ Read the next line
    }

    \\ Actually, the way this is formatted, you'd have to handle the 
    \\ last line after the loop exits but that can be averted in VB 
    \\ by handling the loop conditions at the end

或者,如果您不想先将整个文件读入缓冲区并且希望将您想要的行直接发送到报表,则可以使用布尔标记来标识您是否已阅读您的初始标题...例如,您将标志设置为false,然后一旦读取了第一个数据行,您将其设置为true ...所有当您有条件地将行发送到报告时,如果标志是假的或行是数据。