Discussion Code is mysteriously running twice

  • Wednesday, March 07, 2012 9:44 AM
     
      Has Code

    I have this code it perfectly works fine and then after it completes it runs again and then it crashes. Please enlighten me..

    Sub sortandfilter()
    '----------------------------------------------------------------------------------------
    
    '----------------------------------------------------------------------------------------
    '----------------------------------------------------------------------------------------
    'Application.OnTime TimeValue("10:00:00"), "sortandfilter"
    
    
    Dim oExcel As Excel.Application
    Dim oWB As Workbook
    Set oExcel = New Excel.Application
    Dim DATstr As String
    Dim SpaceAlerts As Worksheet
    Dim FolderPath As String
     Dim WorkBk, workbk2 As Workbook
    Dim NRow As Long
    Dim DestRange As Range
    Dim SourceRange As Range
    Dim passoverrng As Range
    Dim rng As Range
        Dim OutApp As Object
        Dim OutMail As Object
    
        Set rng = Nothing
      
    Dim FileName As String
    
    
     
    DATstr = Format((Date), "yyyymmdd")
    Date = Format((Date), "dd-mm-yyyy")
    
    
    'Creates a new workbook and worksheet and sets a variable for us to refer in this case it is SpaceAlerts
    Set SpaceAlerts = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    Range("B1").Select
        ActiveCell.FormulaR1C1 = " Instance"
        Range("C1").Select
        ActiveCell.FormulaR1C1 = " Name"
        Range("D1").Select
        ActiveCell.FormulaR1C1 = " Name"
        Range("E1").Select
        ActiveCell.FormulaR1C1 = " MB"
        Range("F1").Select
        ActiveCell.FormulaR1C1 = " MB"
        Range("G1").Select
        ActiveCell.FormulaR1C1 = " MB"
        Range("H1").Select
        ActiveCell.FormulaR1C1 = "Used "
        Range("H1").Select
        With Selection.Font
            .Color = -16776961
            .TintAndShade = 0
        End With
        Range("B1:H1").Select
        Selection.Font.Bold = True
        Range("A1").Select
        ActiveCell.FormulaR1C1 = "This is accurate as of " & Date
    'Set SpaceAlerts = ActiveWorkbook.Sheets(1).Activate
    
    ' NRow keeps track of where to insert new rows in the destination workbook.
    NRow = 2
    
    ' Modify this folder path to point to the files you want to use.
     FolderPath = "X:\" & DATstr & "\"
     
     ' Call Dir the first time, pointing it to all Excel files in the folder path.
     FileName = Dir(FolderPath & "MSS_*.xl*")
     
      ' Loop until Dir returns an empty string.
     Do While FileName <> ""
    Set WorkBk = Workbooks.Open(FolderPath & FileName)
    
    ' Set the cell in column A to be the file name.
    
            SpaceAlerts.Range("A" & NRow).Value = FileName
     
    '                           SORT and FILTER HAPPENS HERE
    
        ActiveWorkbook.Worksheets("Sheet1").ListObjects("MyTable").Sort.SortFields. _
            Clear
        ActiveWorkbook.Worksheets("Sheet1").ListObjects("MyTable").Sort.SortFields.Add( _
            Range("MyTable[[#All],[usedPCT]]"), xlSortOnFontColor, xlAscending, , _
            xlSortNormal).SortOnValue.Color = RGB(255, 0, 0)
        Selection.RemoveSubtotal
        With ActiveWorkbook.Worksheets("Sheet1").ListObjects("MyTable").Sort
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
        ActiveSheet.ListObjects("MyTable").Range.AutoFilter Field:=7, Criteria1:= _
            RGB(255, 0, 0), Operator:=xlFilterFontColor
          Range("MyTable[[#Headers],[ServerInstance]]").Select
        Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
       
    
        
        ' Set the source range to be A9 through C9.
            ' Modify this range for your workbooks.
            ' It can span multiple rows.
            Set SourceRange = WorkBk.Worksheets(1).Range("A1:X2000").Offset(1).Resize(Selection.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
        
        ' Set the destination range to start at column B and
            ' be the same size as the source range.
            Set DestRange = SpaceAlerts.Range("B" & NRow)
            Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
               SourceRange.Columns.Count)
        
        DestRange.Value = SourceRange.Value
        
        
         ' Increase NRow so that we know where to copy data next.
            NRow = NRow + DestRange.Rows.Count
            
            ' Close the source workbook without saving changes.
            WorkBk.Close savechanges:=False
            
            ' Use Dir to get the next file name.
            FileName = Dir()
        Loop
        
        ' Call AutoFit on the destination sheet so that all
        ' data is readable.
        [D:D].SpecialCells(xlBlanks).EntireRow.Delete
        SpaceAlerts.Columns.AutoFit
        
       ' ActiveWorkbook.SaveAs FileName:=Range("X1").Value
        
        'SEND EMAIL sub
        
    
        On Error Resume Next
        
        'Only the visible cells in the selection
        'SpaceAlerts.Activate
        
        Set rng = Sheets("Sheet1").Range("A1:X2000").SpecialCells(xlCellTypeVisible)
        
        
        'You can also use a range if you want
        'Set rng = Sheets("YourSheet").Range("D4:D12").SpecialCells(xlCellTypeVisible)
        On Error Resume Next
    
        If rng Is Nothing Then
            MsgBox "The selection is not a range or the sheet is protected" & _
                   vbNewLine & "please correct and try again.", vbOKOnly
            Exit Sub
        End If
    
        With Application
            .EnableEvents = False
            .ScreenUpdating = False
        End With
    
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)
    
        On Error Resume Next
        With OutMail
            
            '.To = "DB_monitor"
            '.CC = ""
            
            .BCC = ""
            .Subject = "SQL Server DB Space > 85%"
            .HTMLBody = RangetoHTML(rng)
            .Send   'or use .Display
        End With
        On Error GoTo 0
    
        With Application
            .EnableEvents = True
            .ScreenUpdating = True
        End With
    
        Set OutMail = Nothing
        Set OutApp = Nothing
        ActiveWorkbook.Close False
    End Sub
    
    Function RangetoHTML(rng As Range)
    ' Changed by Ron de Bruin 28-Oct-2006
    ' Working in Office 2000-2010
        Dim fso As Object
        Dim ts As Object
        Dim TempFile As String
        Dim TempWB As Workbook
     
        TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
     
        'Copy the range and create a new workbook to past the data in
        rng.Copy
        Set TempWB = Workbooks.Add(1)
        With TempWB.Sheets(1)
            .Cells(1).PasteSpecial Paste:=8
            .Cells(1).PasteSpecial xlPasteValues, , False, False
            .Cells(1).PasteSpecial xlPasteFormats, , False, False
            .Cells(1).Select
            Application.CutCopyMode = False
            On Error Resume Next
            .DrawingObjects.Visible = True
            .DrawingObjects.Delete
            On Error GoTo 0
        End With
     
        'Publish the sheet to a htm file
        With TempWB.PublishObjects.Add( _
             SourceType:=xlSourceRange, _
             FileName:=TempFile, _
             Sheet:=TempWB.Sheets(1).Name, _
             Source:=TempWB.Sheets(1).UsedRange.Address, _
             HtmlType:=xlHtmlStatic)
            .Publish (True)
        End With
     
        'Read all data from the htm file into RangetoHTML
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
        RangetoHTML = ts.ReadAll
        ts.Close
        RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                              "align=left x:publishsource=")
     
        'Close TempWB
        TempWB.Close savechanges:=False
     
        'Delete the htm file we used in this function
        Kill TempFile
     
        Set ts = Nothing
        Set fso = Nothing
        Set TempWB = Nothing
    End Function


    ok then it crashes at the line

    [D:D].SpecialCells(xlBlanks).EntireRow.Delete

    take note that this line crashes on the second run not the first run.

    and the thing is i am running this everyday using the ontime method , it was running ok the first few days then it started acting weird.

    Please contribute your suggestions.


    D.Boy



All Replies

  • Wednesday, March 07, 2012 12:08 PM
     
     

    Here are my two normal recopmmendations

    1)  Comment out all the ON Error Statements until you get you code working.  There may be errors that are being skipped over that need to be fixed.

    2) change you VBA error handling in the following menu

    Tools - Options - general Error Trapping - Break on all Errors


    jdweng