删除电子表格中的行,其中<condition>的列为<condition>未知时</condition> </condition>

时间:2009-11-20 12:57:32

标签: excel vba excel-vba excel-2003

我需要在电子表格中找到“过期”和“过期”这个词,但它们出现的列将是可变的,记录(行)的数量也是如此。我需要删除数据中没有这些值的所有行,然后在删除其他数据后总计剩余的数据。有线索吗?

3 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情。

将其放入宏中运行

Sub Macro1()
Dim sheet As Worksheet
Dim usedRange As Range

    Set sheet = ActiveSheet
    Set usedRange = sheet.usedRange

Dim rowCount As Integer
Dim columnCount As Integer
Dim iRow As Integer
Dim iColumn As Integer

    rowCount = usedRange.Rows.Count
    columnCount = usedRange.Columns.Count

    For iRow = rowCount To 1 Step -1
        For iColumn = 1 To columnCount
            If ((InStr(1, LCase(usedRange(iRow, iColumn)), "overdue") > 0) Or (InStr(1, LCase(usedRange(iRow, iColumn)), "due") > 0)) Then
                usedRange.Range(Cells(iRow, 1), Cells(iRow, columnCount)).Delete
            End If
        Next iColumn
    Next iRow

End Sub

答案 1 :(得分:1)

您也可以尝试使用ADO。

Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim strWhere As String
Dim i As Integer

''http://support.microsoft.com/kb/246335

strFile = ActiveWorkbook.FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

strSQL = "SELECT * FROM [Sheet1$] AS s "

rs.Open strSQL, cn, 3, 3

For i = 0 To rs.fields.Count - 1
    strWhere = strWhere & " AND (UCase(s.[" _
        & rs.fields(i).Name & "] ) Not Like '%DUE%' Or s.[" _
        & rs.fields(i).Name & "] Is Null) "
Next

strSQL = strSQL & " WHERE " & Mid(strWhere, 5)
rs.Close

rs.Open strSQL

For i = 0 To rs.fields.Count - 1
    Sheets("Sheet2").Cells(1, i + 1) = rs.fields(i).Name
Next

Worksheets("Sheet2").Cells(2, 1).CopyFromRecordset rs

答案 2 :(得分:1)

Excel应该能够将任何值强制转换为字符串,但错误除外。因此,如果您有返回错误的公式,则可能导致类型不匹配。这是使用Find方法避免该问题的另一种方法。循环遍历列的查找速度可能较慢,但如果您没有大量数据,则不会注意到它。

Sub DeleteOverDue()

    Dim i As Long
    Dim rFound As Range

    'Loop backward through the used range
    For i = Sheet1.usedRange.Rows.Count To 1 Step -1
        'Should find "due" and "overdue" because of xlPart
        Set rFound = Sheet1.usedRange.Cells(i, 1).EntireRow.Find("due", , xlValues, xlPart)
        'If it's not found, delete the row
        If rFound Is Nothing Then
            Sheet1.usedRange.Cells(i, 1).EntireRow.Delete
        End If
    Next i

End Sub

注意:此代码会删除数据,因此请在您的实际数据副本上使用它,直到您知道它适合您。