VBA .AddComment makes script extremely slow?

bertjeiv

New Member
Joined
Sep 23, 2010
Messages
32
Hello all,
I have written a script that compares 2 files and makes a 3rd with the differences and it works fine. i takes about a minute to process the entire task. now i wanted to add some more info in the 3rd file by adding comments to each compared cell by adding this line (just for test variables will be added later)

Cells(r, c).AddComment.Text Text:="Comparator:"

but now the code is EXTREMELY slow. It takes about 30 minutes to process...
is the addcomment slow or am i doing something wrong?

thanks
Bert
 

Excel Facts

Quick Sum
Select a range of cells. The total appears in bottom right of Excel screen. Right-click total to add Max, Min, Count, Average.
Maybe your worksheet is being updated every single time.

Try putting this before your code
Code:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

and try putting this after your code
Code:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True

If it still takes too long, would it be possible for you to post your code using the bbcode?
 
Upvote 0
I will try it now, I already have turned of screenupdating in my scrip but i'll add:
Code:
Application.Calculation = xlCalculationManual 
Application.EnableEvents = False
I just noticed that it really slows down on 1 certain page one with 165k cells being compared. it starts fast lets say 1000cells/second and near the ends it has slowed down to 10cells/second.

when i comment out the
Code:
Cells(r, c).AddComment.Text Text:="Comparator:"
then it does not slow down at all.

cheers
 
Upvote 0
That changed a lot!
my script without comments
107seconds
with comments
2770seconds (46 minutes)

with your suggestion, with comments
262 seconds

thanks a lot!
 
Upvote 0
yes it is always the same but just for testing
adding comments also really inflates the filesize from 1.2mb to about 12mb. I need to add more info to those comments so I'm afraid that what I want is a bit much. Saving the 12mb file takes about 10minutes...
 
Upvote 0
It shouldn't take anywhere near that long to save a file that size.
 
Upvote 0
Code:
Sub CompareWorksheets(ws1 As Worksheet, ws2 As Worksheet, sheetname As String, count As Integer, rptWB As Workbook)
Dim r, counter, cellstotal As Long, c As Integer
Dim lr1 As Long, lr2 As Long, lc1 As Integer, lc2 As Integer
Dim maxR As Long, maxC As Integer, cf1 As String, cf2 As String
Dim DiffCount As Long
Dim foundcell As Range, lastcell As Range, firstcell As Range, needle As String, spares As Integer
Dim spareflag As Boolean, diffflag As Boolean, strpos1 As Integer, strpos2 As Integer, filledflag1 As Boolean, filledflag2 As Boolean

    

    Application.DisplayAlerts = True
    

    
    'get number rows and columns from reference
    With ws1.UsedRange
        lr1 = .Rows.count
        lc1 = .Columns.count
    End With

    'filter spares
    needle = "spare"
    spares = 0
    With Range(Cells(10, 1), Cells(lr1, lc1))
        Set lastcell = .Cells(.Cells.count)
    End With
 
        Set foundcell = ws1.Cells.Find(What:=needle, After:=Cells(10, 1), LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)
        If Not foundcell Is Nothing Then
            firstaddr = foundcell.Address
            spares = spares + 1
            Do
                Debug.Print foundcell.Address
                Set foundcell = ws1.Cells.FindNext(After:=foundcell)
                spares = spares + 1
            Loop While Not foundcell Is Nothing And foundcell.Address <> firstaddr
        End If

    'MsgBox spares & " #spares"
    
        'get number of cells for statusbar
    If ws1.UsedRange.Cells.count > ws2.UsedRange.Cells.count Then
    cellstotal = ws1.UsedRange.Cells.count
    Else
    cellstotal = ws2.UsedRange.Cells.count
    End If
    
    'get number rows and columns from target
    With ws2.UsedRange
        lr2 = .Rows.count
        lc2 = .Columns.count
    End With
    
            
    maxR = lr1
    maxC = lc1
    If maxR < lr2 Then maxR = lr2
    If maxC < lc2 Then maxC = lc2
    DiffCount = 0
    counter = 0
    For r = 9 To maxR
    
        'Application.StatusBar = "Comparing cells " & Format(c / maxC, "0 %") & "..."
        spareflag = False
        diffflaf = False
        For c = 1 To maxC
        counter = counter + 1
        Application.StatusBar = counter & "/" & cellstotal
        Workbooks("Comparator.xlsm").Worksheets("Sheet1").ProgressBar1.Width = counter & "/" & cellstotal
            cf1 = ""
            cf2 = ""
            On Error Resume Next
            cf1 = UCase(ws1.Cells(r, c).FormulaLocal)
            cf2 = UCase(ws2.Cells(r, c).FormulaLocal)
            cf1o = ws1.Cells(r, c).FormulaLocal
            cf2o = ws2.Cells(r, c).FormulaLocal
            On Error GoTo 0
            strpos1 = InStr(cf1, "SPARE")
            strpos2 = InStr(cf2, "SPARE")
            
            If IsEmpty(ws1.Cells(r, c)) = False Then
            filledflag1 = True
            End If
            If IsEmpty(ws2.Cells(r, c)) = False Then
            filledflag2 = True
            End If
            If strpos1 <> 0 Or strpos2 <> 0 Then
            spareflag = True
            End If
            If cf1 <> cf2 Then
            diffflag = True
                DiffCount = DiffCount + 1
                Cells(r, c).Formula = "'" & cf1 & " <> " & cf2
            End If
            Cells(r, c).AddComment.Text Text:="Comparator:"
           
        Next c
        With Range(Cells(r, 1), Cells(r, maxC))
            If filledflag1 = True And filledflag2 = False Then
            .Interior.ColorIndex = 44
            ElseIf filledflag1 = False And filledflag2 = True Then
            .Interior.ColorIndex = 46
            ElseIf spareflag = True Then
            .Interior.ColorIndex = 8
            ElseIf diffflag = True Then
            .Interior.ColorIndex = 3
            Else
            .Interior.ColorIndex = 19
            End If
        End With
    Next r
    'format results
    With Range(Cells(9, 1), Cells(maxR, maxC))
        With .Borders(xlEdgeTop)
            .LineStyle = xlContinuous
            .Weight = xlHairline
        End With
        With .Borders(xlEdgeRight)
            .LineStyle = xlContinuous
            .Weight = xlHairline
        End With
        With .Borders(xlEdgeLeft)
            .LineStyle = xlContinuous
            .Weight = xlHairline
        End With
        With .Borders(xlEdgeBottom)
            .LineStyle = xlContinuous
            .Weight = xlHairline
        End With
        On Error Resume Next
        With .Borders(xlInsideHorizontal)
            .LineStyle = xlContinuous
            .Weight = xlHairline
        End With
        With .Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .Weight = xlHairline
        End With
        On Error GoTo 0
    End With
    Columns("A:IV").ColumnWidth = 20
    
    Set rptWB = Nothing

    Workbooks("Compare.xlsx").Worksheets("Result_Summary").Cells(2 + count, 1).Formula = sheetname
    Workbooks("Compare.xlsx").Worksheets("Result_Summary").Cells(2 + count, 2).Formula = DiffCount
    Workbooks("Compare.xlsx").Worksheets("Result_Summary").Cells(2 + count, 3).Formula = spares
    'MsgBox DiffCount & " cells contain different formulas!", vbInformation, _
     '   "Compare " & ws1.Name & " with " & ws2.Name
End Sub
Code:
Sub TestCompareWorksheets()
    ' compare two different worksheets in the active workbook
    ' CompareWorksheets Worksheets("Sheet1"), Worksheets("Sheet2")
    ' compare two different worksheets in two different workbooks
    
    'declare variables
    Dim sheetname As String
    Dim i As Integer
    Dim rptWB As Workbook
    Dim CopyRange As Range
    Dim start_time, end_time
start_time = Now()

        
    'prepare application for faster comparisson
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    Application.StatusBar = "Creating the report..."
    Application.DisplayAlerts = False
    Application.DisplayStatusBar = True
    Application.AutoRecover.Enabled = False
    
    'create new workbook with compare results
    Set rptWB = Workbooks.Add
    Application.ScreenUpdating = False
    ActiveWorkbook.SaveAs "Compare.xlsx"
    While Worksheets.count > 1
        Worksheets(1).Delete
    Wend
    ActiveSheet.Name = "Result_Summary"
    Cells(1, 1).Formula = "Result Summary"
    Cells(2, 1).Formula = "Sheet"
    Cells(2, 2).Formula = "Amount differences"
    Cells(2, 3).Formula = "Amount spares"
    
    For i = 1 To Workbooks("ARC12_2011_04_13_1124.xls").Sheets.count
    
    sheetname = Workbooks("ARC12_2011_04_13_1124.xls").Sheets(i).Name
    'add sheet to results workbook with same name
    Workbooks("Compare.xlsx").Sheets.Add
    ActiveSheet.Name = sheetname
    'Application.StatusBar = "Processing " & sheetname
    Cells(1, 1).Formula = "exists in 1 not in 2"
    Cells(1, 1).Interior.ColorIndex = 44
    Cells(1, 2).Formula = "exists in 2 not in 1"
    Cells(1, 2).Interior.ColorIndex = 46
    Cells(1, 3).Formula = "contains spare"
    Cells(1, 3).Interior.ColorIndex = 8
    Cells(1, 4).Formula = "differences"
    Cells(1, 4).Interior.ColorIndex = 3
    Cells(1, 5).Formula = "identical"
    Cells(1, 5).Interior.ColorIndex = 19
    
    'copy headers
    Set CopyRange = Union(Workbooks("ARC12_2011_04_13_1124.xls").Worksheets(sheetname).Rows(5), Workbooks("ARC12_2011_04_13_1124.xls").Worksheets(sheetname).Rows(6), Workbooks("ARC12_2011_04_13_1124.xls").Worksheets(sheetname).Rows(7), Workbooks("ARC12_2011_04_13_1124.xls").Worksheets(sheetname).Rows(8))
    CopyRange.Copy
    With Workbooks("Compare.xlsx").Worksheets(sheetname)
        Range("A5").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False
    End With
    
    
    'call comparison function
    CompareWorksheets Workbooks("ARC12_2011_04_13_1124.xls").Worksheets(sheetname), _
        Workbooks("ARC12_2010_05_20_1157.xls").Worksheets(sheetname), sheetname, i, rptWB
    Next i
    end_time = Now()
MsgBox (DateDiff("s", start_time, end_time))

    Application.StatusBar = False
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

End Sub
all the workbooks are hardcoded now for faster testing
it works like this:
TestCompareWorksheets() is run when a button is pressed on the worksheet
it first creates a new workbook and makes a sheet with some basic info which it will complete later with data of the processed files
second it takes the reference workbook and iterates through the pages
each pass it adds a new page to the results workbook (Compare.xlsx) and adds a color code legend.then it copies the header cells from the reference book to the results book. then it calls the CompareWorksheets function.

the CompareWorksheets is pretty straightforward i guess.
first it counts the amount of "spares" then it does some stuff to get the row and column count of the workbooks being compared then it iterates through all cells setting some flags for color code later on and at the end some basic formatting.

I'm going to try to upload the results workbook somewhere i hope one of you guys can try and open it and save it again because for me its really slow.

no macros in these files.
version with comment: 12mb
https://rapidshare.com/files/1451919198/Compare.xlsx

version without comment: 1.2mb
https://rapidshare.com/files/631633514/Compare.xls

thank you very much so far guys I really appreciate it
 
Last edited:
Upvote 0
I've tried downloading your files 3 times and each time after waiting the 5 minutes I get an error from rapidshare so I can't test....

If I had to guess, I think you're somehow applying some formatting to the entire sheet(s), not just your used range. after your macro runs and you press F5 and select Special and in that dialog box select Last Cell and hit OK, where does it take you?
 
Upvote 0

Forum statistics

Threads
1,224,596
Messages
6,179,807
Members
452,943
Latest member
Newbie4296

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