vba - deleting a row from tab in workbook

PrettyMess

Board Regular
Joined
Feb 10, 2015
Messages
66
I have inherited a workbook with a load of VBA code in it and I'm currently trying to get my head around it but I'm struggling a bit.

The workbook currently seems to delete the top row of the data in the "Date of last turn" tab which starts in cell "A3" I have tried to combat a lot of the copying and pasting this person has put into the vba but im not sure if im just missing something and maybe a fresh set of eyes could point me in the right direction.

Any help would be greatly appreciated

Code:
Sub SortWorkbook()`
    Dim msganswer As Integer
    msganswer = MsgBox("--------------------------------------------This programme can take up to 1 min to finish--------------------------------------------" & vbNewLine & "Programme will update all records into individual tabs based for each coach." & vbNewLine & "Any coaches with a nominal diameter recorded on or below the alert level will be highlighted in yellow.", vbOKOnly, "NOTE:")`

    'Deletes all tabs except for "All Data" and "Shortcuts" and "Date of Last Turn"
    Dim s
      Application.DisplayAlerts = False
      For Each s In Sheets
         If s.Name <> "All Data" And s.Name <> "Shortcuts" And s.Name         
    <> "Date of Last Turn" Then
        s.Delete
 End If
      Next
      Application.DisplayAlerts = True`
    '-----------------------------------------------------------------------------------------------------------------------------
    Range("A3:AC10000").Interior.ColorIndex = 0
    Range("E3:E10000").ClearComments
    '-------------------------------------------------------------------------------
    Dim y As Double

    For y = 3 To 10000

    If Cells(y, "E").Value = 0 And Cells(y, "C").Value > 0 Then
    Cells(y, "E").AddComment
    Cells(y, "E").Comment.Text Text:="Data not recorded on lathe turning sheet."
    End If

    Next y
    '-----------------------------------------------------------------------------------------------------------------------------
    'Highlights rows based on "alert" values corresponding to each class of coach
    Dim coach As Double
    Dim nomdia As Double
    Dim k As Double
    Dim c3k As Integer
    Dim c4k As Integer
    Dim sanditepowercar As Integer
    Dim sanditetrailer As Integer
    Dim c450 As Integer
    Dim gmloco As Integer
    Dim c9k As Integer
    Dim genvan As Integer
    Dim c9kloco As Integer

    For k = 3 To Rows.Count

    coach = Cells(k, "C").Value
    nomdia = Cells(k, "E").Value

    '-----------------------------------------------------------------------------------------------------------------------------
    c3k = Worksheets("Shortcuts").Range("G29")
    c4k = Worksheets("Shortcuts").Range("G30")
    sanditepowercar = Worksheets("Shortcuts").Range("G31")
    sanditetrailer = Worksheets("Shortcuts").Range("G32")
    c450 = Worksheets("Shortcuts").Range("G33")
    gmloco = Worksheets("Shortcuts").Range("G34")
    c9k = Worksheets("Shortcuts").Range("G35")
    genvan = Worksheets("Shortcuts").Range("G36")
    c9kloco = Worksheets("Shortcuts").Range("G37")
    '-----------------------------------------------------------------------        ------------------------------------------------------

   'This section use the function LastRow and SheetExists
        Dim My_Range As Range
        Dim FieldNum As Long
        Dim CalcMode As Long
        Dim ViewMode As Long
        Dim ws2 As Worksheet
        Dim Lrow As Long
        Dim cell As Range
        Dim CCount As Long
        Dim WSNew As Worksheet
        Dim ErrNum As Long
        Dim DestRange As Range
        Dim Lr As Long

        'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
        'and the header of the first column, D is the last column in the filter range.
        'You can also add the sheet name to the code like this :
        'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
        'No need that the sheet is active then when you run the macro when you use this.
        Set My_Range = Worksheets("All Data").Range("A3:AC" & LastRow(Worksheets("All Data")))
        'Set My_Range = Range("A3:AB" & LastRow(ActiveSheet))
        My_Range.Parent.Select

        If ActiveWorkbook.ProtectStructure = True Or _
           My_Range.Parent.ProtectContents = True Then
            MsgBox "Sorry, not working when the workbook or worksheet is protected", _
                   vbOKOnly, "Copy to new worksheet"
            Exit Sub
        End If

        'This example filters on the first column in the range(change the field if needed)
        'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
        FieldNum = 3

        'Turn off AutoFilter
        My_Range.Parent.AutoFilterMode = False

        'Change ScreenUpdating, Calculation, EnableEvents, ....
        With Application
            CalcMode = .Calculation
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
        End With
        ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
ActiveSheet.DisplayPageBreaks = False

'Add a worksheet to copy the a unique list and add the CriteriaRange
Set ws2 = Worksheets.Add

With ws2
    'first we copy the Unique data from the filter field to ws2
    My_Range.Columns(FieldNum).AdvancedFilter _
            Action:=xlFilterCopy, _
            CopyToRange:=.Range("A4"), Unique:=True

    'loop through the unique list in ws2 and filter/copy to a new sheet
    Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
    For Each cell In .Range("A4:A" & Lrow)

        My_Range.Parent.Select
        'Filter the range
        My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
         Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")

        'Check if there are no more then 8192 areas(limit of areas)
        CCount = 0
        On Error Resume Next
        CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
                 .Areas(1).Cells.Count
        On Error GoTo 0
        If CCount = 0 Then
            MsgBox "There are more than 8192 areas for the value: " & cell.Value _
                 & vbNewLine & "It is not possible to copy the visible data." _
                 & vbNewLine & "Tip: Sort your data before you use this macro.", _
                   vbOKOnly, "Split in worksheets"
        Else
            'Add a new worksheet or set a reference to a existing sheet
            If SheetExists(cell.Text) = False Then
                Set WSNew = Worksheets.Add(After:=Sheets(Sheets.Count))
                On Error Resume Next
                WSNew.Name = cell.Value
                If Err.Number > 0 Then
                    ErrNum = ErrNum + 1
                    WSNew.Name = "Error_" & Format(ErrNum, "0000")
                    Err.Clear
                End If
                On Error GoTo 0
                Set DestRange = WSNew.Range("A1")
            Else
                Set WSNew = Sheets(cell.Text)
                Lr = LastRow(WSNew)
                Set DestRange = WSNew.Range("A" & Lr + 1)
            End If

            'Copy the visible data to the worksheet
            My_Range.SpecialCells(xlCellTypeVisible).Copy
            With DestRange
                .Parent.Select
                ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
                ' Remove this line if you use Excel 97
                .PasteSpecial Paste:=8
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                .PasteSpecial xlPasteComments

                Application.CutCopyMode = False
                .Select
            End With
        End If

        ' Delete the header row if you copy to a existing worksheet
        'If Lr > 1 Then WSNew.Range("A" & Lr + 1).EntireRow.Delete

        'Show all data in the range
        My_Range.AutoFilter Field:=FieldNum

    Next cell

    'Delete the ws2 sheet
    On Error Resume Next
    Application.DisplayAlerts = False
    .Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

End With

'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False

If ErrNum > 0 Then
    MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
         & vbNewLine & "There are characters in the name that are not allowed" _
         & vbNewLine & "in a sheet name or the worksheet already exist."
End If

'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = CalcMode
End With

    '-----------------------------------------------------------------------        ------------------------------------------------------
    'This section prompts the user to sort sheets in either ascending or descending order
    Dim i As Integer
     Dim j As Integer
     Dim iAnswer As VbMsgBoxResult

     Prompt the user as which direction they wish to
     ' sort the worksheets.

    iAnswer = MsgBox("Sort Sheets in Ascending Order? i.e. 3301, 3302,         etc..." & Chr(10) _
     & "Clicking No will sort in Descending Order", _
     vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
     For i = 1 To Sheets.Count
     For j = 1 To Sheets.Count - 1

              If the answer is Yes, then sort in ascending order.

     If iAnswer = vbYes Then
     Application.ScreenUpdating = False
     If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
     Sheets(j).Move After:=Sheets(j + 1)
     End If

      If the answer is No, then sort in descending order.

     ElseIf iAnswer = vbNo Then
     Application.ScreenUpdating = False
     If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
     Sheets(j).Move After:=Sheets(j + 1)
     End If
     End If
     Next j
     Next i
     Application.ScreenUpdating = True
     '----------------------------------------------------------------------        -------------------------------------------------------
             'Ensures "Shortcuts" & "All Data" and "Date of Last  Turn" is         kept in         front of all other tabs
             Sheets("All Data").Move before:=Sheets(1)
             Sheets("Shortcuts").Move before:=Sheets(1)
             Sheets("Date of Last Turn").Move before:=Sheets(1)
    '-----------------------------------------------------------------------        ------------------------------------------------------
    'Section copies first two rows in worksheet "All Data" and pastes on         new worksheets
    Dim Source As Worksheet
        Set Source = ThisWorkbook.Sheets("All Data")
        Application.ScreenUpdating = False
        For Each WS In ThisWorkbook.Worksheets
           If WS.Name <> Source.Name And WS.Name <> "Date of Last Turn" Then
                Source.Rows("1:2").Copy
                WS.Rows("1:2").Insert Shift:=xlDown
                WS.Rows("1:2").PasteSpecial Paste:=8
                'WS.Rows("1:2").PasteSpecial xlPasteValues
                'WS.Rows("1:2").PasteSpecial xlPasteColumnWidths

            End If
        Next WS
        Application.CutCopyMode = False
        Application.ScreenUpdating = True
    '-----------------------------------------------------------------------        ------------------------------------------------------
      Section deletes two rows inserted by section above in the "Shortcuts" tab.
    Dim Source2 As Worksheet
        Set Source2 = ThisWorkbook.Sheets("Shortcuts")
        Application.ScreenUpdating = False
        For Each WS In ThisWorkbook.Worksheets
            If WS.Name = Source2.Name Then
                Source2.Rows("1:2").EntireRow.Delete

            End If
        Next WS
        Application.CutCopyMode = False
        Application.ScreenUpdating = True
    '-----------------------------------------------------------------------        ------------------------------------------------------
    'Section deletes two rows inserted by section above in the "Date of         Last Turn" tab.
    'Dim Source3 As Worksheet
        'Set Source3 = ThisWorkbook.Sheets("Date of Last Turn")
        'Application.ScreenUpdating = False
        'For Each WS In ThisWorkbook.Worksheets
            'If WS.Name = Source3.Name Then
                'Source3.Rows("1:2").EntireRow.Delete
                'Source3.Rows("1:2").EntireRow.ClearContents

            'End If
        'Next WS
        'Application.CutCopyMode = False
        'Application.ScreenUpdating = True
    -----------------------------------------------------------------------                ------------------------------------------------------
             Section fixes bug where a row for "3311" appeared in each new         worksheet.
            Dim celltxt As String
            celltxt = ActiveSheet.Range("C3").Text
            For Each WS In ThisWorkbook.Worksheets
                If WS.Name <> "All Data" And WS.Name <> "3311" And WS.Name         <> "Shortcuts" Then
                WS.Rows("3").EntireRow.Delete
                End If
            Next WS
    ------------------------------------------------------------------------        -----------------------------------------------------
    Section fixes bug where values in sheet 3311 are duplicated
    Sheets("3311").Range("A3:AE10000").RemoveDuplicates Columns:=Array(1, 3, 4), Header:=xlYes
    ------------------------------------------------------------------------        -----------------------------------------------------

    Dim msganswer2 As Integer
    msganswer2 = MsgBox("Programme has finished running.", vbOKOnly, "Programme End")

    End Sub

    Function LastRow(sh As Worksheet)
        On Error Resume Next
        LastRow = sh.Cells.Find(What:="*", _
                        After:=sh.Range("A1"), _
                        LookAt:=xlPart, _
                        LookIn:=xlValues, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
        On Error GoTo 0
    End Function


    Function SheetExists(SName As String, _
                 Optional ByVal WB As Workbook) As Boolean
    'Chip Pearson
        On Error Resume Next
        If WB Is Nothing Then Set WB = ThisWorkbook
        SheetExists = CBool(Len(WB.Sheets(SName).Name))
    End Function

    Function Sort_Active_Book()
     Dim i As Integer
     Dim j As Integer
     Dim iAnswer As VbMsgBoxResult

    Prompt the user as which direction they wish to
     sort the worksheets.

     iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
     & "Clicking No will sort in Descending Order", _
     vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
     For i = 1 To Sheets.Count
     For j = 1 To Sheets.Count - 1

     If the answer is Yes, then sort in ascending order.

     If iAnswer = vbYes Then
     If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
     Sheets(j).Move After:=Sheets(j + 1)
     End If

     If the answer is No, then sort in descending order.

     ElseIf iAnswer = vbNo Then
     If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
     Sheets(j).Move After:=Sheets(j + 1)
     End If
     End If
     Next j
     Next i
     End Function


    Function InsertOnTopOfEachSheet()
        Dim WS As Worksheet, Source As Worksheet
        Set Source = ThisWorkbook.Sheets("All Data") 'Modify to suit.
        Application.ScreenUpdating = False
        For Each WS In ThisWorkbook.Worksheets
         If WS.Name <> Source.Name And WS.Name <> "Date of Last Turn" Then
         Source.Rows("1:2").Copy
        WS.Rows("1:2").Insert Shift:=xlDown
        'WS.Rows("1:2").PasteSpecial Paste:=8
        'WS.Rows("1:2").PasteSpecial xlPasteValues
        WS.Rows("1:2").PasteSpecial xlPasteColumnWidths

    End If
        Next WS
        Application.CutCopyMode = False
        Application.ScreenUpdating = True
    End Function

    Sub RemoveDuplicates1()

    Range("A3").Select
        ActiveSheet.Range("$A$1:$AC$203").RemoveDuplicates Columns:=Array(1, 3, 4), _
    Header:=xlYes

    Dim celltxt As String
    celltxt = ActiveSheet.Range("C3").Text
    If InStr(1, celltxt, "3311") Then
Rows("3:3").Select
Selection.Delete
    End If

    End Sub

    Sub blblblblb()
    Range("E3:E10000").ClearComments

    Dim y As Double

    For y = 3 To 10000

    If Cells(y, "E").Value = 0 And Cells(y, "C").Value > 0 Then
    Cells(y, "E").AddComment
    Cells(y, "E").Comment.Text Text:="Data not recorded on lathe turning sheet."
    End If

    Next y

    End Sub


    Sub ghghg()
    Sheets("3311").Range("A3:AE10000").RemoveDuplicates Columns:=Array(1, 3, 4), Header:=xlYes
    End Sub
 

Excel Facts

Square and cube roots
The =SQRT(25) is a square root. For a cube root, use =125^(1/3). For a fourth root, use =625^(1/4).

Forum statistics

Threads
1,214,614
Messages
6,120,519
Members
448,968
Latest member
Ajax40

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top