vba编程 - 删除整行,不包含

时间:2014-09-26 10:05:41

标签: excel vba excel-vba

我是宏和VBA的新手,所以这可能很容易。

我需要过滤公司列表,以便从excel-tab中删除不匹配分支代码的公司。

更确切地说:

  • company.xls包含公司的完整列表,其中列为N. 包含分支码
  • branch.xls,A列包含相关的分支代码,其中 必须用于过滤company.xls
  • 中的comapnies
  • company.xls中没有匹配的公司 branchcode应该从company.xls的tab1到tab2中删除。

我希望它有意义!?

提前感谢您的回复。

Function Search_String(x As String) As Boolean
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim Contained As Boolean
Contained = True

'We use the ActiveSheet but you can replace this with
'Sheets("MySheet")if you want
With Sheets("codes")

    'We select the sheet so we can change the window view
    .Select

    'Set the first and last row to loop through
    Firstrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

    'We loop from Lastrow to Firstrow (bottom to top)
    For Lrow = Lastrow To Firstrow Step -1

        'We check the values in the A column in this example
        With .Cells(Lrow, "A") 'Column letter for codes sheet

            If Not IsError(.Value) Then
                If InStr(x, .Value) Then Contained = False
            End If
        End With
    Next Lrow
End With

Search_String = Contained
End Function


Sub Filtrer()
Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim CalcMode As Long
Dim ViewMode As Long

With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

With Sheets("search (14)") 'Sheet name with rows to be deleted
    'We select the sheet so we can change the window view
    .Select

    'If you are in Page Break Preview Or Page Layout view go
    'back to normal view, we do this for speed
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView

    'Turn off Page Breaks, we do this for speed
    .DisplayPageBreaks = False

    'Set the first and last row to loop through
    Firstrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

    'We loop from Lastrow to Firstrow (bottom to top)
    For Lrow = Lastrow To Firstrow Step -1

        With .Cells(Lrow, "N") 'Change this to the correct Sheets column that needs deleting
            If Not IsError(.Value) Then
                If Search_String(.Value) Then .EntireRow.Delete
            End If
        End With
    Next Lrow

End With

ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .Calculation = CalcMode
End With

End Sub

1 个答案:

答案 0 :(得分:1)

如果我错了,请纠正我。现在你想让用户输入表名 columnName

然后以下代码将为您提供帮助。

Dim SheetName As String
Dim ColumnName As String

SheetName = InputBox("Enter the Sheet Name ?") ' Ex Sheet1
ColumnName = InputBox("Enter the column Name ?") ' Ex N

With Sheets(SheetName) ' Replace this line
With .Cells(Lrow, ColumnName) ' Replace this line