vba - 从工作簿中的选项卡中删除一行

时间:2016-07-19 10:02:16

标签: excel-vba vba excel

我继承了一个载有大量VBA代码的工作簿,而我现在正试图解决这个问题,但我有点挣扎。

目前,工作簿似乎删除了"最后一个日期"中的数据的顶行。在单元格中开始的标签" A3"我试图打击这个人放入vba的很多复制和粘贴,但我不确定我是否只是缺少一些东西,也许一双新鲜的眼睛可以指向正确的方向。

非常感谢任何帮助

    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

2 个答案:

答案 0 :(得分:0)

可能是它没有删除前两行,它只添加两个空行?这一行插入了两行。

WS.Rows("1:2").Insert Shift:=xlDown

答案 1 :(得分:0)

我想出来这在bug修复部分是愚蠢的,然后我不得不删除两个类别,在每个标签中删除两行。感谢大家的帮助