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

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

我需要过滤一个公司列表,这样,不匹配branchcode的公司将从excel标签中删除。

更确切地说:

  • company.xls包含公司的完整列表,其中列N包含分支代码
  • branch.xls,A列包含相关性的分支代码,必须使用它来过滤company.xls中的共同点
  • 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 

纠正我,如果我错了。现在你想让用户inputsheetnamecolumnName

然后下面的代码将帮助你。

 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