Consulting

Page 2 of 4 FirstFirst 1 2 3 4 LastLast
Results 21 to 40 of 63

Thread: Selecting and deleting rows based on criteria

  1. #21
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    Quote Originally Posted by Beatrix View Post
    Sorry I guess It's me,my English etc.. couldn't explain it properly. I meant data security policies, compliance policy etc.. I need to change my data but keep the structure as it is..
    hi there. re to snb's comment: snb states that workbooks or worksheets may be protected. so remove the protection first. ----- and if you are not familiar with, adopt snb's codes to your workbook/worksheet structure. ----- from 'enabling the user to select the first row to start deleting rows' requirement i assume that the files are generated by some non MS office applications (or by different departments or or by different employees). so they dont have the same table structure and need to be made similar.
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  2. #22
    VBAX Mentor
    Joined
    May 2010
    Location
    London
    Posts
    307
    Location
    Hi All ,


    There is no ws/wb protection in the spreadsheets.

    I attached 2 sample xls. Over all it's 4 files including before/after. The range starts from Row13 in all ws in Sample1. The range slightly changes in Sample2 - it's Row10 in some tabs. Apart from blank rows and blank columns I also need to remove the entire row where it says NE, NW, YH, EM, WM, E, L, IL, OL, SE, SW. At the end of the range there is a row which gives source info and bullets/numbering for some notes. I need to keep them as it is.

    I only need to delete blank rows and blank columns and some certain rows in the range. Because first row of the range might change that's why I've thought mesage box would be an effective solution in this case. However you guys are expert so know much much better than I do, you might suggest other options?

    PS: Sample2 has got some hidden worksheets which shouldn't be included to the process. Also some tabs in Sample2 has got data validation drop down lists which should remain as it is. ( I don't know if this would cause any issues)
    . There are many spreadsheets in this format that's why I want to create one folder and to be able to run the script for all of them.


    Cheers
    B.
    Attached Files Attached Files
    Sub Learning VBA()

    Do
    Practice Most Useful VBA Examples
    Loop Until Become an Expert in VBA

    End Sub

  3. #23
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    hi.

    i see you left 2 blank rows between tables and footnotes. so i took it into account when determining the Last Rows of the tables.

    try this with copies of your files.


    including snb's offer for specialcells method
    Sub Del_Rows_n_Cols_on_Condition_AllWS_AllWB_Same_Folder()
    'http://www.vbaexpress.com/forum/showthread.php?48681-Selecting-and-deleting-rows-based-on-criteria
    
    
        Dim wb As Workbook, ws As Worksheet
        Dim fRange As Range, delRng As Range
        Dim FirstRowQ As Variant
        Dim i As Long, FR As Long, LR As Long, LC As Long
        Dim fName, fPath As String
        
        fPath = "C:\Files\" 'change to suit. include final \
        fName = Dir(fPath & "*.xls*")
        Do While fName <> ""
            Set wb = Workbooks.Open(fPath & fName)
            wb.Worksheets(1).Activate
            FirstRowQ = MsgBox(wb.Name & vbLf & vbLf & "Is the first row the same in each worksheet?", vbYesNoCancel, "First Row Decision")
            If FirstRowQ = vbYes Then
                Set fRange = Application.InputBox("Please Select the First Row of the Range", "First Row Selection", Type:=8)
                FR = fRange.Row
                For Each ws In wb.Worksheets
                    With ws
                        LR = .Cells.Find("(1) Includes", , , xlPart, xlByRows, xlPrevious).Row - 3
                        LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                        Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                        delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues 'filters table for matches in Column C
                        .AutoFilter.Range.Rows.Delete 'deletes all rows of auto filter range
                        .AutoFilterMode = False
                        delRng.Columns(1).SpecialCells(4).EntireRow.Delete 'deletes all rows of blank cells in the table's first column (which is Column A)
                        .Rows(FR).SpecialCells(4).EntireColumn.Delete 'deletes all columns of blank cells in the selected First Row
                    End With
                Next ws
            ElseIf FirstRowQ = vbNo Then
                For Each ws In wb.Worksheets
                    With ws
                        .Activate
                        Set fRange = Application.InputBox("Select the first row in each worksheet", "First Row Selection", Type:=8)
                        FR = fRange.Row
                        LR = .Cells.Find("(1) Includes", , , xlPart, xlByRows, xlPrevious).Row - 3
                        LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                        Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                        delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                        .AutoFilter.Range.Rows.Delete
                        .AutoFilterMode = False
                        delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                        .Rows(FR).SpecialCells(4).EntireColumn.Delete
                    End With
                Next ws
            Else
                MsgBox "You cancelled the code execution. Quitting...", vbOKOnly, "QUIT"
                wb.Close SaveChanges:=False
                Exit Sub
            End If
            wb.Close SaveChanges:=True
            fName = Dir()
        Loop
    End Sub
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  4. #24
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    second sample workbook has some sheets with formulas. deleting rows and columns may cause REF errors if formulas are dependent to those rows/cols.
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  5. #25
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    BTW, if there is a pattern for all sheets in all books to determine the first row, ie all sheets have the same values in a cell (say A5, A7, A13, etc) in a column (say Col A), using a variable will be more efficient than making the user select a cell. ----- if there is, you can delete many lines from the code i posted and make life easy for the users. ----- assume all sheets have a common value such as "Performance Report As Of xx.xx.xxxx". (here x's are changing). this value may be in cell A13 in some sheets, in A8 for some other sheet, etc. the following method finds the first occurence of "Performance Report As Of" bit of this text and returns its row number as the First Row number.
    FR = .Cells.Find("Performance Report As Of", , , xlPart, xlByRows, xlNext).Row
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  6. #26
    VBAX Mentor
    Joined
    May 2010
    Location
    London
    Posts
    307
    Location
    hi mancubus.thanks for your reply. The code looks good and worked perfectly on S1 however gave run time error for S2. "91" -Object variable or With block variable not set. I don't know what's causing this error, hidden tabs may be? I said No to first message box as the first row is not same in each ws in S2 then it stopped and gave this error. Did you manage to run it on S2?



    Quote Originally Posted by mancubus View Post
    hi.

    i see you left 2 blank rows between tables and footnotes. so i took it into account when determining the Last Rows of the tables.

    try this with copies of your files.


    including snb's offer for specialcells method
    Sub Del_Rows_n_Cols_on_Condition_AllWS_AllWB_Same_Folder()
    'http://www.vbaexpress.com/forum/showthread.php?48681-Selecting-and-deleting-rows-based-on-criteria
    
    
        Dim wb As Workbook, ws As Worksheet
        Dim fRange As Range, delRng As Range
        Dim FirstRowQ As Variant
        Dim i As Long, FR As Long, LR As Long, LC As Long
        Dim fName, fPath As String
        
        fPath = "C:\Files\" 'change to suit. include final \
        fName = Dir(fPath & "*.xls*")
        Do While fName <> ""
            Set wb = Workbooks.Open(fPath & fName)
            wb.Worksheets(1).Activate
            FirstRowQ = MsgBox(wb.Name & vbLf & vbLf & "Is the first row the same in each worksheet?", vbYesNoCancel, "First Row Decision")
            If FirstRowQ = vbYes Then
                Set fRange = Application.InputBox("Please Select the First Row of the Range", "First Row Selection", Type:=8)
                FR = fRange.Row
                For Each ws In wb.Worksheets
                    With ws
                        LR = .Cells.Find("(1) Includes", , , xlPart, xlByRows, xlPrevious).Row - 3
                        LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                        Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                        delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues 'filters table for matches in Column C
                        .AutoFilter.Range.Rows.Delete 'deletes all rows of auto filter range
                        .AutoFilterMode = False
                        delRng.Columns(1).SpecialCells(4).EntireRow.Delete 'deletes all rows of blank cells in the table's first column (which is Column A)
                        .Rows(FR).SpecialCells(4).EntireColumn.Delete 'deletes all columns of blank cells in the selected First Row
                    End With
                Next ws
            ElseIf FirstRowQ = vbNo Then
                For Each ws In wb.Worksheets
                    With ws
                        .Activate
                        Set fRange = Application.InputBox("Select the first row in each worksheet", "First Row Selection", Type:=8)
                        FR = fRange.Row
                        LR = .Cells.Find("(1) Includes", , , xlPart, xlByRows, xlPrevious).Row - 3
                        LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                        Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                        delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                        .AutoFilter.Range.Rows.Delete
                        .AutoFilterMode = False
                        delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                        .Rows(FR).SpecialCells(4).EntireColumn.Delete
                    End With
                Next ws
            Else
                MsgBox "You cancelled the code execution. Quitting...", vbOKOnly, "QUIT"
                wb.Close SaveChanges:=False
                Exit Sub
            End If
            wb.Close SaveChanges:=True
            fName = Dir()
        Loop
    End Sub
    Sub Learning VBA()

    Do
    Practice Most Useful VBA Examples
    Loop Until Become an Expert in VBA

    End Sub

  7. #27
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    Hi Beatrix.

    Sorry for that.

    Pls add below line after With ws
     If .Visible = True Then
    and below line before End With
    End If
    for both YES and NO responses.

    Let me know if it does not fix the problem.
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  8. #28
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    hi again.

    in the second workbook first footnote is "1. NOTES" and not "(1) Includes". it throws error on this line. and maybe other workbook have different footnotes. so it will be hard to detect the last row of the worksheets for coding purposes. and considering there are not always 2 blank rows between tables and footnotes, it will be even harder.

    but i see a common text in all worksheets which is Source: X. if it exists at the end of all tables in all worksheets in all workbooks, we can use it to determine the last rows of data tables. but if not, to my knowledge, you should find a pattern which is common to all worksheets.

    assuming exists in all worksheets i modified the code as below.

    i noticed that the first worksheet is hidden. so i added a few lines to handle it.

    Sub Del_Rows_n_Cols_on_Condition_AllWS_AllWB_Same_Folder()
    'http://www.vbaexpress.com/forum/showthread.php?48681-Selecting-and-deleting-rows-based-on-criteria
    
        Dim wb As Workbook, ws As Worksheet
        Dim fRange As Range, delRng As Range
        Dim FirstRowQ As Variant
        Dim i As Long, FR As Long, LR As Long, LC As Long
        Dim fName, fPath As String
        
        'fPath = "C:\Files\" 'change to suit. include final \
        fPath = "C:\Users\Attila\test\beax\" 'change to suit. include final \
        fName = Dir(fPath & "*.xls*")
        Do While fName <> ""
            Set wb = Workbooks.Open(fPath & fName)
            For i = 1 To Worksheets.Count
                If Worksheets(i).Visible Then
                    Worksheets(i).Select
                    Exit For
                End If
            Next i
            FirstRowQ = MsgBox(wb.Name & vbLf & vbLf & "Is the first row the same in each worksheet?", vbYesNoCancel, "First Row Decision")
            If FirstRowQ = vbYes Then
                Set fRange = Application.InputBox("Please Select the First Row of the Range", "First Row Selection", Type:=8)
                FR = fRange.Row
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            LR = .Cells.Find("Source", , , xlPart, xlByRows, xlPrevious).Row - 1
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            ElseIf FirstRowQ = vbNo Then
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            .Activate
                            Set fRange = Application.InputBox("Select the first row in each worksheet", "First Row Selection", Type:=8)
                            FR = fRange.Row
                            LR = .Cells.Find("Source", , , xlPart, xlByRows, xlPrevious).Row - 1
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            Else
                MsgBox "You cancelled the code execution. Quitting...", vbOKOnly, "QUIT"
                wb.Close SaveChanges:=False
                Exit Sub
            End If
            wb.Close SaveChanges:=True
            fName = Dir()
        Loop
    End Sub


    or if you dont bother loosing blank rows between tables and footnotes, (and since the cell of that row in Col A is blank) the row that contains the word "Source" as well, you can use the first code.
    Sub Del_Rows_n_Cols_on_Condition_AllWS_AllWB_Same_Folder()
    'http://www.vbaexpress.com/forum/showthread.php?48681-Selecting-and-deleting-rows-based-on-criteria
    
        Dim wb As Workbook, ws As Worksheet
        Dim fRange As Range, delRng As Range
        Dim FirstRowQ As Variant
        Dim i As Long, FR As Long, LR As Long, LC As Long
        Dim fName, fPath As String
        
        'fPath = "C:\Files\" 'change to suit. include final \
        fPath = "C:\Users\Attila\test\beax\" 'change to suit. include final \
        fName = Dir(fPath & "*.xls*")
        Do While fName <> ""
            Set wb = Workbooks.Open(fPath & fName)
            For i = 1 To Worksheets.Count
                If Worksheets(i).Visible Then
                    Worksheets(i).Select
                    Exit For
                End If
            Next i
            FirstRowQ = MsgBox(wb.Name & vbLf & vbLf & "Is the first row the same in each worksheet?", vbYesNoCancel, "First Row Decision")
            If FirstRowQ = vbYes Then
                Set fRange = Application.InputBox("Please Select the First Row of the Range", "First Row Selection", Type:=8)
                FR = fRange.Row
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            LR = .Cells.Find("*", , , xlPart, xlByRows, xlPrevious).Row
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            ElseIf FirstRowQ = vbNo Then
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            .Activate
                            Set fRange = Application.InputBox("Select the first row in each worksheet", "First Row Selection", Type:=8)
                            FR = fRange.Row
                            LR = .Cells.Find("*", , , xlPart, xlByRows, xlPrevious).Row
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            Else
                MsgBox "You cancelled the code execution. Quitting...", vbOKOnly, "QUIT"
                wb.Close SaveChanges:=False
                Exit Sub
            End If
            wb.Close SaveChanges:=True
            fName = Dir()
        Loop
    End Sub




    PS: in some worksheets of "Removing rows n columns_S2_before.xls" workbook the column that have string criteria (NE, NW, IL, etc) is B rather than C. so the code threw an error there when testing. i inserted a column to fix it.
    Last edited by mancubus; 01-23-2014 at 02:47 PM.
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  9. #29
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,638
    @macubus

    You might use the following procedure:

    for each it in Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW")
      cells.replace it,"12/0"
    next
    cells.specialcells(2,16).entirerow.delete

  10. #30
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    thanks snb. ----- worksheets "Table 23" and "Table 24" of "Removing....._S2_Before.xls" made me think, when preparing the sample files for the VBAX, the OP has accidentally deleted Column C. but worksheets "Table 11", "Table 12", etc display criteria cells in column B. ----- maybe using replace function for only columns B and C for full match to convert the criteria array elements into "error formulas" and then deleting their rows will suffice. ----- perhaps like this. as 12/0 returns a date i used "=12/0" instead, replaced 2 (xlCellTypeConstants) with -4123 (xlCellTypeFormulas) and limited the range to columns 2 and 3 of delRange. line1:
    For Each it In Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW")
    line2:
        Range(Cells(FR, 2), Cells(LR, 3)).Cells.Replace it, "=12/0", xlWhole
    line3:
    Next
    line4:
    Range(Cells(FR, 2), Cells(LR, 3)).SpecialCells(-4123, 16).EntireRow.Delete
    below line is the same as line4:
    Range(Cells(FR, 2), Cells(LR, 3)).SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Delete
    thus, if the above code is used, the three lines that contain the word "AutoFilter" must be deleted from previous procedures for both YES and NO responses.
    PS: "-----" means a new paragraph. in my office coumputer i cannot use html tags for line breaks, etc in VBAX. and i dont duplicate the problem in other forums like mrexcel, excelforum, ozgrid, etc. sorry for the inconvenience.
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  11. #31
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,638
    Although you can use:

    Cells(5,5)=[0/0]
    you can't use it in a replace action. It has to be a string.

    e.g.

    Sub M_snb()
       Columns(2).Resize(, 2).Replace "A", "=0/0"
    End Sub

  12. #32
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    thanks. did the same: ......Replace it, "=12/0" and it returned division by 0 error in mathing cells.
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  13. #33
    VBAX Mentor
    Joined
    May 2010
    Location
    London
    Posts
    307
    Location
    Hey mancubus!

    Sorry for the late response.

    This is a great code and works fine for this 2 samples. Thanks for considering all criteria. At least I know which bits need to be changed when I run the script for other workbooks with different formats

    I appreciate for spending your time on this.

    @snb n @ D_Marcel : Thanks very much for your time and for all your help too

    Cheers
    B.


    Quote Originally Posted by mancubus View Post
    hi again.

    in the second workbook first footnote is "1. NOTES" and not "(1) Includes". it throws error on this line. and maybe other workbook have different footnotes. so it will be hard to detect the last row of the worksheets for coding purposes. and considering there are not always 2 blank rows between tables and footnotes, it will be even harder.

    but i see a common text in all worksheets which is Source: X. if it exists at the end of all tables in all worksheets in all workbooks, we can use it to determine the last rows of data tables. but if not, to my knowledge, you should find a pattern which is common to all worksheets.

    assuming exists in all worksheets i modified the code as below.

    i noticed that the first worksheet is hidden. so i added a few lines to handle it.

    Sub Del_Rows_n_Cols_on_Condition_AllWS_AllWB_Same_Folder()
    'http://www.vbaexpress.com/forum/showthread.php?48681-Selecting-and-deleting-rows-based-on-criteria
    
        Dim wb As Workbook, ws As Worksheet
        Dim fRange As Range, delRng As Range
        Dim FirstRowQ As Variant
        Dim i As Long, FR As Long, LR As Long, LC As Long
        Dim fName, fPath As String
        
        'fPath = "C:\Files\" 'change to suit. include final \
        fPath = "C:\Users\Attila\test\beax\" 'change to suit. include final \
        fName = Dir(fPath & "*.xls*")
        Do While fName <> ""
            Set wb = Workbooks.Open(fPath & fName)
            For i = 1 To Worksheets.Count
                If Worksheets(i).Visible Then
                    Worksheets(i).Select
                    Exit For
                End If
            Next i
            FirstRowQ = MsgBox(wb.Name & vbLf & vbLf & "Is the first row the same in each worksheet?", vbYesNoCancel, "First Row Decision")
            If FirstRowQ = vbYes Then
                Set fRange = Application.InputBox("Please Select the First Row of the Range", "First Row Selection", Type:=8)
                FR = fRange.Row
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            LR = .Cells.Find("Source", , , xlPart, xlByRows, xlPrevious).Row - 1
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            ElseIf FirstRowQ = vbNo Then
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            .Activate
                            Set fRange = Application.InputBox("Select the first row in each worksheet", "First Row Selection", Type:=8)
                            FR = fRange.Row
                            LR = .Cells.Find("Source", , , xlPart, xlByRows, xlPrevious).Row - 1
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            Else
                MsgBox "You cancelled the code execution. Quitting...", vbOKOnly, "QUIT"
                wb.Close SaveChanges:=False
                Exit Sub
            End If
            wb.Close SaveChanges:=True
            fName = Dir()
        Loop
    End Sub


    or if you dont bother loosing blank rows between tables and footnotes, (and since the cell of that row in Col A is blank) the row that contains the word "Source" as well, you can use the first code.
    Sub Del_Rows_n_Cols_on_Condition_AllWS_AllWB_Same_Folder()
    'http://www.vbaexpress.com/forum/showthread.php?48681-Selecting-and-deleting-rows-based-on-criteria
    
        Dim wb As Workbook, ws As Worksheet
        Dim fRange As Range, delRng As Range
        Dim FirstRowQ As Variant
        Dim i As Long, FR As Long, LR As Long, LC As Long
        Dim fName, fPath As String
        
        'fPath = "C:\Files\" 'change to suit. include final \
        fPath = "C:\Users\Attila\test\beax\" 'change to suit. include final \
        fName = Dir(fPath & "*.xls*")
        Do While fName <> ""
            Set wb = Workbooks.Open(fPath & fName)
            For i = 1 To Worksheets.Count
                If Worksheets(i).Visible Then
                    Worksheets(i).Select
                    Exit For
                End If
            Next i
            FirstRowQ = MsgBox(wb.Name & vbLf & vbLf & "Is the first row the same in each worksheet?", vbYesNoCancel, "First Row Decision")
            If FirstRowQ = vbYes Then
                Set fRange = Application.InputBox("Please Select the First Row of the Range", "First Row Selection", Type:=8)
                FR = fRange.Row
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            LR = .Cells.Find("*", , , xlPart, xlByRows, xlPrevious).Row
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            ElseIf FirstRowQ = vbNo Then
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            .Activate
                            Set fRange = Application.InputBox("Select the first row in each worksheet", "First Row Selection", Type:=8)
                            FR = fRange.Row
                            LR = .Cells.Find("*", , , xlPart, xlByRows, xlPrevious).Row
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            delRng.AutoFilter Field:=3, Criteria1:=Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW"), Operator:=xlFilterValues
                            .AutoFilter.Range.Rows.Delete
                            .AutoFilterMode = False
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete 'WARNING: if a cell in a blank row is selected all columns will be deleted.
                        End If
                    End With
                Next ws
            Else
                MsgBox "You cancelled the code execution. Quitting...", vbOKOnly, "QUIT"
                wb.Close SaveChanges:=False
                Exit Sub
            End If
            wb.Close SaveChanges:=True
            fName = Dir()
        Loop
    End Sub




    PS: in some worksheets of "Removing rows n columns_S2_before.xls" workbook the column that have string criteria (NE, NW, IL, etc) is B rather than C. so the code threw an error there when testing. i inserted a column to fix it.
    Sub Learning VBA()

    Do
    Practice Most Useful VBA Examples
    Loop Until Become an Expert in VBA

    End Sub

  14. #34
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    You are welcome. I am glad it helped.
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  15. #35
    VBAX Mentor
    Joined
    May 2010
    Location
    London
    Posts
    307
    Location
    Hi mancubus. I missed this bit. That string criteria, does it need to be in the same column in all ws?? I've thought it might be anywhere within the range and it would be still ok . I guess that's too much to expect That's why Table 11-12-13-18-19 still have that specific rows


    Quote Originally Posted by mancubus View Post
    PS: in some worksheets of "Removing rows n columns_S2_before.xls" workbook the column that have string criteria (NE, NW, IL, etc) is B rather than C. so the code threw an error there when testing. i inserted a column to fix it.
    Sub Learning VBA()

    Do
    Practice Most Useful VBA Examples
    Loop Until Become an Expert in VBA

    End Sub

  16. #36
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    hi again.

    looking the messages i post, it seemed the code was not copmplete to me.

    i'll try to tidy all the code up a bit. and comment some lines in case someone will need it in the future. will post it when ready
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  17. #37
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    Quote Originally Posted by Beatrix View Post
    Hi mancubus. I missed this bit. That string criteria, does it need to be in the same column in all ws?? I've thought it might be anywhere within the range and it would be still ok . I guess that's too much to expect That's why Table 11-12-13-18-19 still have that specific rows
    hi Beatrix.

    you are a bit earlier than me.

    i first assumed they are in column B. after seeing that workbook, replaced column C with Columns B and C.

    i'll take into account that part within the scope of my previous post. i mean which column they are in will not matter. but you must be careful that all rows containing the defined strings (NE, NW, IL, etc) at whole will be deleted. if a cell's value is NEW its row will not be deleted. but if its value is NE it will be deleted. OK?
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

  18. #38
    VBAX Mentor
    Joined
    May 2010
    Location
    London
    Posts
    307
    Location
    Yep that sounds perfect


    Quote Originally Posted by mancubus View Post
    hi Beatrix.

    you are a bit earlier than me.

    i first assumed they are in column B. after seeing that workbook, replaced column C with Columns B and C.

    i'll take into account that part within the scope of my previous post. i mean which column they are in will not matter. but you must be careful that all rows containing the defined strings (NE, NW, IL, etc) at whole will be deleted. if a cell's value is NEW its row will not be deleted. but if its value is NE it will be deleted. OK?
    Sub Learning VBA()

    Do
    Practice Most Useful VBA Examples
    Loop Until Become an Expert in VBA

    End Sub

  19. #39
    Knowledge Base Approver VBAX Wizard
    Joined
    Apr 2012
    Posts
    5,638
    I still think this is sufficient for range starting in row 13:

    Sub M_snb()
        For Each sh In Sheets
            sh.UsedRange.Columns(1).Offset(12).SpecialCells(4).EntireRow.Delete
            sh.Rows(11).SpecialCells(4).EntireColumn.Delete
        Next
    End Sub

  20. #40
    VBAX Guru mancubus's Avatar
    Joined
    Dec 2010
    Location
    "Where I lay my head is home" :D
    Posts
    2,644
    hi.
    try this with copies of your files. not tested.
    pls keep in mind that Last Row of range to be processed is determined by the word "Source".

    Sub Del_Rows_n_Cols_on_Condition_AllWS_AllWB_Same_Folder()
    'http://www.vbaexpress.com/forum/showthread.php?48681-Selecting-and-deleting-rows-based-on-criteria
    
    
        Dim wb As Workbook, ws As Worksheet
        Dim fRange As Range, delRng As Range
        Dim FirstRowQ As Variant
        Dim i As Long, FR As Long, LR As Long, LC As Long
        Dim fName, fPath As String
        
        fPath = "C:\Files\" 'change to suit. include final \
        'fPath = "C:\Users\Attila\test\beax\" 'change to suit. include final \
        
        fName = Dir(fPath & "*.xls*")
        'Dir function returns a string representing the first file in the specified folder.
        'using it without any arguments returns the next file: fName = Dir()
        
        Do While fName <> "" 'start loop
            
            Set wb = Workbooks.Open(fPath & fName)
            'open the file. assign it to wb variable
            
            For i = 1 To wb.Worksheets.Count
            'if here are any hidden sheets, select the first visible worksheet.
                If Worksheets(i).Visible Then
                    Worksheets(i).Select
                    Exit For 'when the first visible worksheet is selected exit loop.
                End If
            Next i
            
            FirstRowQ = MsgBox(wb.Name & vbLf & vbLf & "Is the first row the same in each worksheet?", vbYesNoCancel, "First Row Decision")
            'offer user 2 choices (YES, NO) to base the fist row selection method and another (CANCEL) to stop the code execution.
            
            If FirstRowQ = vbYes Then
            'user clicked the YES button. the row of selected cell in the next step will be used as First Row in all worksheets.
                
                Set fRange = Application.InputBox("Please Select the First Row of the Range", "First Row Selection", Type:=8)
                'make user select the cell whose row number will be used as first row in all worksheets
                
                FR = fRange.Row
                'assign selected cell's row number to FR variable
                
                For Each ws In wb.Worksheets
                'loop all worksheets in the opened workbook
                    
                    With ws
                        If .Visible = True Then
                        'check if worksheet is visible. if visible continue next line.
                            
                            LR = .Cells.Find("Source", , , xlPart, xlByRows, xlPrevious).Row - 1
                            'find the first occurence of string "Source" from bottom-up. return its row number. -1 means 1 row above Source will be Last Row
                            
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            'find the first occurence of any string/value from right-left. return its column number as Last Column.
                            
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            'set the range to delete rows and columns based on condition usng the variables determined above: FR,LR, and LC. 1 is for column A.
                            
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            'determine the blank cells in the first column of the set range and delete their rows.
                            
                            For Each it In Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW")
                                delRng.Cells.Replace it, "=12/0", xlWhole
                            Next
                            'loop all cells in the range for all string criteria and if found a match change it to "=12/0" formula to display a formula error in cell.
                            'it may be "=15/0" or "=0/0", whatever. this is done to use specialcells method to get all cells with formula errors.
                            
                            delRng.SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Delete
                            'or =
                            'delRng.SpecialCells(-4123, 16).EntireRow.Delete
                            'any of the above lines will delete the rows that contain a formula error.
                            
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete
                            'determine the blank cells in the first row of the set range and delete their columns.
                        End If
                    End With
                
                Next ws
            
            ElseIf FirstRowQ = vbNo Then
            'user clicked the NO button. the row of selected cell in each worksheet will be used as First Row in each woksheets separately.
    
    
                For Each ws In wb.Worksheets
                    With ws
                        If .Visible = True Then
                            .Activate 'in order to select a range in a worksheet that sheet must be selected first.
                            Set fRange = Application.InputBox("Select the first row in each worksheet", "First Row Selection", Type:=8)
                            FR = fRange.Row
                            LR = .Cells.Find("Source", , , xlPart, xlByRows, xlPrevious).Row - 1
                            LC = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
                            Set delRng = .Range(.Cells(FR, 1), .Cells(LR, LC))
                            delRng.Columns(1).SpecialCells(4).EntireRow.Delete
                            For Each it In Array("NE", "NW", "YH", "EM", "WM", "E", "L", "IL", "OL", "SE", "SW")
                                delRng.Cells.Replace it, "=12/0", xlWhole
                            Next
                            .Rows(FR).SpecialCells(4).EntireColumn.Delete
                        End If
                    End With
                Next ws
            
            Else
            'user clicked the CANCEL button.
                
                MsgBox "You cancelled the code execution. Quitting...", vbOKOnly, "QUIT"
                'inform the user about cancellation.
                
                wb.Close SaveChanges:=False
                'close the first workbook without saving.
                
                Exit Sub
                'exit procedure.
            End If
            
            wb.Close SaveChanges:=True
            'save and close the workbook whose rows and columns are deleted
            fName = Dir()
            'return the next file
        
        Loop
        'go back to Do While fName <> "" line to process the next workbook.
    
    
    End Sub
    PLS DO NOT PM; OPEN A THREAD INSTEAD!!!

    1) Posting Code
    [CODE]PasteYourCodeHere[/CODE]
    (or paste your code, select it, click # button)

    2) Uploading File(s)
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    Replace company specific / sensitive / confidential data. Include so many rows and sheets etc in the uploaded workbook to enable the helpers visualize the data and table structure. Helpers do not need the entire workbook.

    3) Testing the Codes
    always back up your files before testing the codes.

    4) Marking the Thread as Solved
    from Thread Tools (on the top right corner, above the first message)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •