簡體   English   中英

使用VBA刪除特定范圍的行

[英]Deleting a specific range of rows with VBA

我是VBA的新手,所以這可能是一個基本問題。

每周我都會導出包含各種數據的文件。 在此文件中,我每次必須刪除相同范圍的行。 我可以通過基於單元格位置定義一個范圍來輕松實現此操作,但是有時此范圍開始的位置不在同一行。 但是,范圍每次都以相同的值開始並以相同的值結束。

我是否有可能自動刪除從開始到底部范圍內的所有行? 無需根據單元格位置指定范圍?

這就是你的樣子

Option Explicit
Sub TargetRows()

    Dim wb As Workbook
    Dim wsTarget As Worksheet
    Dim startCell As Range
    Dim endCell As Range
    Dim startMatch As String
    Dim endMatch As String

    startMatch = "Artikelgroep: Promotional material"
    endMatch = "Artikelgroep: (totaal)"

    Set wsTarget = ThisWorkbook.Worksheets("Sheet2") 'change as required
    Set startCell = wsTarget.Columns(1).EntireColumn.Find(what:=startMatch, LookIn:=xlValues, lookat:=xlPart)
    Set endCell = wsTarget.Columns(1).EntireColumn.Find(what:=endMatch, LookIn:=xlValues, lookat:=xlPart)

    Dim deleteRange As Range

    If Not startCell Is Nothing And Not endCell Is Nothing And startCell.Row <= endCell.Row Then
        Set deleteRange = wsTarget.Range("A" & startCell.Row & ":A" & endCell.Row)
    Else
        Debug.Print "1 or both values not found or end text found before start text."
    End If

    If Not deleteRange Is Nothing Then deleteRange.EntireRow.Delete
End Sub

參考:

特定列的Excel VBA查找方法 (@shai rado)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM