【问题标题】:Delete contents below a search using VBA in Excel在 Excel 中使用 VBA 删除搜索下方的内容
【发布时间】:2015-04-02 09:09:34
【问题描述】:

我正在尝试使用宏来删除 excel 中某个单词/短语之后的数据。

问题是单元格位置可能会根据报表运行/导出后电子表格中的行数而有所不同。如果可能的话,我需要一个解决方案来定位某个短语(使用我假设的查找功能)并从文本可能所在的位置删除 30 个单元格(没有 cet 单元格)。

这可能吗?

【问题讨论】:

    标签: excel vba find cell


    【解决方案1】:

    这是可能的,但你想要的细节并不是最清楚的。这是一些可以帮助您入门的代码。它在工作表上的所有单元格中查找给定的短语。如果找到它,它会将低于该单元格的 30 个单元格添加到预定删除的组中。搜索完所有单元格后,它会删除收集到的组。

    由于我们正在遍历要从中删除的集合,因此我收集要删除的单元格(使用联合)并在循环关闭后删除它们。

    这可能不是最快的代码,因为它会搜索 UsedRange 中的所有单元格,但它应该适用于大多数用途。

    Sub deleteBelowPhrase()
    
        Dim cell As Range
        Dim sht As Worksheet
    
        Dim phrase As String
        Dim deleteRows As Integer
    
        'these are the parameters
        phrase = "DELETE BELOW ME"
        deleteRows = 30
    
        'assumes you are searching the active sheet
        Set sht = ActiveSheet
    
        Dim del_range As Range
        Dim del_cell As Range
    
        For Each cell In sht.UsedRange
    
            'check for the phrase in the cell
            If InStr(cell.Value2, phrase) > 0 Then
    
                'get a reference to the range to delete
                Set del_cell = sht.Range(cell.Offset(1), cell.Offset(deleteRows))
    
                'create object to delete or add to existing
                If del_range Is Nothing Then
                    Set del_range = del_cell
                Else
                    Set del_range = Union(del_range, del_cell)
                End If
            End If
    
        Next cell
    
        'delete the block of cells that are collected
        del_range.Delete xlShiftUp
    
    End Sub
    

    之前

    之后

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 2017-01-27
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多