如果单元格包含某个字符串,则删除表行

时间:2018-10-23 09:39:40

标签: excel vba excel-vba

我想要一个代码,该代码可遍历电子表格不同工作表中的所有表,并在第1列和第2列中包含值LeaveName和PositionLeaver的情况下删除一行。

还可以返回已删除行的工作表的名称。

我的代码是以下atm:

Sub Leavers()

Dim LeaverName As String
LeaverName = InputBox("Enter name of the employee leaving in the following format (Surname, First Name)", "Adding New Joiner to Hub")
Dim PositionLeaver As String
Position = InputBox("Enter new joiner Position (A, C, SC, PC, MP, Partner, Admin, Analyst, Director)", "Assigning New Joiner to a position")
'Input Name and Position of the employeee leaving and stores it (Could be improved with user form...)


Dim tbl As ListObject
Dim sht As Worksheet
Dim MyTable As ListObject

'Loop through each sheet and table in the workbook
For Each sht In ThisWorkbook.Worksheets
    For Each tbl In sht.ListObjects 'loop through all tables
        'To omit certain tables you can do the below
        If tbl.Name <> "Table2" And tbl.Name <> "Table3" And tbl.Name <> "Table5" And tbl.Name <> "Table7" _
        And tbl.Name <> "Table9" And tbl.Name <> "Table11" And tbl.Name <> "Table13" And tbl.Name <> "Table15" Then ...

在这一点上,我不太确定如何解决这个问题。

谢谢你们!

1 个答案:

答案 0 :(得分:1)

这似乎起作用。您只需要遍历每个工作表和每个表(已启动),然后遍历表主体的每一行。我认为Select Case在这里适合您排除表的列表。

Sub x()

Dim ws As Worksheet, t As ListObject, r As Long, b As Boolean

For Each ws In Worksheets
    For Each t In ws.ListObjects
        Select Case t.Name
            Case "Table2", "Table3", "Table5", "Table7", "Table9", "Table11", "Table13", "Table15"
                'do nothing
            Case Else
                For r = t.DataBodyRange.Rows.Count To 1 Step -1
                    If t.DataBodyRange(r, 1) = "LeaverName" And t.DataBodyRange(r, 2) = "PositionLeaver" Then
                        t.DataBodyRange(r, 1).EntireRow.Delete
                        b = True
                    End If
                Next r
        End Select
    Next t
Next ws

If not b Then
    MsgBox ("No employee named " & LeaverName & " with the position " & PositionLeaver & _
                        " could be found." & vbNewLine & vbNewLine & "Double check the details and try again using the correct format.")
End If

End Sub