Consulting

Results 1 to 5 of 5

Thread: Calculate Percent Error

  1. #1
    VBAX Regular
    Joined
    Nov 2018
    Posts
    75
    Location

    Calculate Percent Error

    Hello All,

    I am attempting to calculate a percent error with this code and I am not getting the right result. So the value in "A4" is -53, and should return a percent error of 75 percent. Any thoughts?
    Sub CalculatePercentError()
    'Calculate the errors in cells
    Worksheets("Generalized Report").Activate
        If Worksheets("Generalized Report").range("A4").Value = 0 Then 'Division by 0 error will occur
            Worksheets("Generalized Report").range("A6").Value = Null
        Else
            Worksheets("Generalized Report").range("A6").Value = Abs(range("A4").Value \ (WorksheetFunction.Sum(Worksheets("Contract").range("H2:H10000")))) * 100
        End If
    End Sub

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Try this

    Sub CalculatePercentError()
    'Calculate the errors in cells
    
        With Worksheets("Generalized Report")
        
            If .Range("A4").Value = 0 Then 'Division by 0 error will occur
            
                .Range("A6").Value = Null
            Else
           
                .Range("A6").Value = Abs(.Range("A4").Value \ Application.Sum(Worksheets("Contract").Range("H2:H10000")))
                .Range("A6").NumberFormat = "0.0%"
            End If
        End With
    End Sub
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  3. #3
    VBAX Regular
    Joined
    Nov 2018
    Posts
    75
    Location
    Worked like a charm, Thanks!

  4. #4
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    As it worked, for your info, the only 'real' change I made was to make sure that Range("A4") referred to the Generalized workbook, your code left it referring to whatever was the activeworkbook, the rest was just cosmetic/better coding practices/my coding style.
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  5. #5
    VBAX Regular
    Joined
    Nov 2018
    Posts
    75
    Location
    Yes rereading my code I just caught that. But if I say "Acivate X workbook" wouldn't the code assume everything below was referring to said workbook?

Tags for this Thread

Posting Permissions

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