如何使用excel vba中的范围函数删除特定行

时间:2013-12-28 07:23:12

标签: excel-vba vba excel

如果特定列值以1开头,我想删除Excel工作表中的所有行。

例如,如果A1:A的值范围从1开始,那么我想使用excel vba删除所有这些行。

如何获得它?

  Dim c As Range
Dim SrchRng

 Set SrchRng = Sheets("Output").UsedRange
Do
   Set c = SrchRng.Find("For Men", LookIn:=xlValues)
  If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing

4 个答案:

答案 0 :(得分:0)

Dim Value As String
Dim CellName As String
Dim RowNumber As Long
Do While Value <> ""
    CellName = "A" + RowNumber
    Value = ActiveSheet.Cells(GetRowNumber(CellName), GetColumnNumber(CellName)).Value
    If Mid(Value, 1, 1) = "2" Then
       ActiveSheet.Range("A" & RowNumber).EntireRow.Delete
    End If
    RowNumber = RowNumber + 1
Loop

Private Function GetColumnNumber(ByVal CellName As String) As Long
    For L = 1 To 26
        If Left(CellName, 1) = Chr(L + 64) Then
            GetColumnNumber = L
            Exit For
        End If
    Next
End Function
Private Function GetRowNumber(ByVal CellName As String) As Long
    GetRowNumber = CLng(Mid(CellName, 2))
End Function    

答案 1 :(得分:0)

您可能正在推动Excel vba中合理的操作范围。

考虑将Excel文件导入Microsoft Access。

然后,您可以编写2个删除查询,它们将快速运行:

DELETE FROM MyTable WHERE col1 like '2*'

DELETE FROM MyTable WHERE col2 LIKE '*for men*' OR col3 LIKE '*for men*'

删除这些记录后,您可以将数据导出到新的Excel文件。

此外,您可以编写Access宏来导入Excel文件,运行“删除查询”,并将数据导出回Excel。

你可以在不编写一行VBA代码的情况下完成所有这些工作。

答案 2 :(得分:0)

这是必需的代码,其中包含有关其工作原理的注释。将工作表和列号提供给子并调用它,例如删除第2行,表格(“myWorksheet”):

   Sub DeleteRows(columnNumber as Integer, ws as WorkSheet)

    Dim x as long, lastRow as Long

    ' get the last used row
    lastRow = ws.cells(1000000, columnNumber).end(xlUp).Row

    'loop backwards from the last row and delete applicable rows
    For x = lastRow to 1 Step -1

       ' if the cell starts with a number...
       If IsNumeric(Left(ws.Cells(x, columnNumber), 1) Then
          'Delete it the row if it's equaal to 1
          If Left(ws.Cells(x, columnNumber), 1) = 1 Then ws.Rows(x &":"& x).Delete
       End If
    Next x

    End Sub

答案 3 :(得分:-1)

您可以尝试:

export App from "./App/App"