如何使用.address函数以删除行?

时间:2019-04-05 00:32:48

标签: excel vba

我有一堆.xls文件,在文件的开头有6行垃圾邮件,在A列的任意行中有1行带有文本“ Not分类”的行。我有以下代码删除了第一个6行,然后找到带有正确文本的单元格,但是我不知道如何选择该行,因为我的理解是Find函数像A10一样返回,并且我不知道如何拆分引用以进行选择第10行。

我相信地址功能应该可以在这方面提供帮助,但是我很难使其正常工作。在上面的路径中,是存储我的文件位置的变量,而x是包含有问题的文本的单元格。

Do while files <>""
    Workbooks.Open(path & files).ActiveSheet.Rows("1:6").Delete
    Set x = ActiveWorkbook.ActiveSheet.Range("A:A").Find("Not Classified")
    If Not x Is Nothing Then
        x.Clear 
        'Obviously this only clears the cell with the offending text and I 
        'want to delete the whole row
    End If
    ActiveWorkbook.Close savechanges:=True
    files = Dir()
Loop

我相信地址功能应该可以在这方面提供帮助,但是我很难使其正常工作。在上面的路径中,是存储我的文件位置的变量,而x是包含有问题的文本的单元格。

2 个答案:

答案 0 :(得分:1)

Option Explicit

Sub test()

    Dim strSearchValue As String
    Dim LastRow As Long
    Dim rngSearch As Range, rngPosition As Range

    With ThisWorkbook.Worksheets("Sheet1")

        strSearchValue = "Not Classified"
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row '<- Find lastrow to create a range. No need to use thw whole column.

        Set rngSearch = .Range("A1:A" & LastRow) '<- Set your range

        Set rngPosition = rngSearch.Find(strSearchValue) '<- Find the position of the value

        If Not rngPosition Is Nothing Then '<- To avoid error check if the position is not nothing

            MsgBox rngPosition.Address '<- Message box with the address

        End If

        'How to delete row a row. Have in mind that when you delete you must go backwards - from bottom to top to avoid breaking indexing.
        .Rows(rngPosition.Row).EntireRow.Delete

    End With

End Sub

答案 1 :(得分:0)

您可以生成两个范围的并集(行1:6和包含“未分类”的行),然后将其删除。

  dim r as variant

  Do while files <>""
    with Workbooks.Open(path & files)
      with .worksheets(1)  '<~~ know what worksheet you're dealing with
        r = application.match("Not Classified", .range("A:A"), 0)

        if iserror(r) then
            .range("A1:A6").entirerow.Delete
        else
            .range("A1:A6, A" & r).entirerow.Delete
        end if

      end with
      .Close savechanges:=True
    end with
    files = Dir()
  Loop