我需要在电子表格中找到“过期”和“到期”这个词,但它们出现的列将是可变的,记录(行)的数量也是如此。我需要删除数据中没有这些值的所有行,然后在其他行被删除后合计留在工作表上的数据。有什么线索吗?
问问题
445 次
3 回答
1
Excel 应该能够将任何值强制转换为字符串,但错误除外。因此,如果您有返回错误的公式,则可能导致类型不匹配。这是使用 Find 方法的另一种方法,可以避免该问题。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
注意:此代码会删除数据,因此请在您的真实数据副本上使用它,直到您知道它对您有用。
于 2012-07-23T16:52:47.467 回答
1
You could also try something with 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
于 2009-11-20T20:59:24.703 回答
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
于 2009-11-20T13:15:05.687 回答