简体   繁体   中英

Why do I get at run time error when looping into the next worksheet even though the code executed correctly for the first worksheet?

I have come to a point in my coding where well asked google questions are just not helping me anymore. I have two For loops in my code. They execute correctly for the first Worksheet I set in the loop in my Workbook. However changing to the next Worksheet gives a runtime error:

  • runtime error 13 if I use Application.Average
  • runtime error 1004 if I use Application.WorksheetFunction.Average

What I am trying to do:
I have data from measurements. These are organized in the different Worksheets for different temperature ranges. I want to loop through the relevant columns in the relevant worksheets in my data to find the average values of these columns. In the end I would like to save the averages to my first Worksheet for the corresponding headers. (I haven't written any code for this last part yet.)

Any help is very much appreciated.

Option Explicit

Sub TestAv()

    Dim ColCount As Long
    Dim ws As Worksheet
    Dim LastRow As Long
    Dim j, k, ColCount2, wsCount As Long
    Dim rngAv As Range
    Dim rngAverage As Double
    Dim Lr As Long

    Dim newBook As Workbook
    Dim firstSheet As Worksheet

    Set newBook = ActiveWorkbook
    Set firstSheet = newBook.Sheets(1)

    Application.ScreenUpdating = False
    ' making firstSheet representable
    ColCount = newBook.Worksheets(2).Columns.Count ' all TCs should have been measured for the first temperature
    newBook.Worksheets(2).Activate
    Range(Cells(1, 2), Cells(1, ColCount)).Copy
    firstSheet.Activate
    firstSheet.Range("B1").Select
    firstSheet.Paste
    Application.CutCopyMode = False
    Application.CutCopyMode = True
    firstSheet.Range("A1").Value = "Temperaturen"
    firstSheet.Name = "Mittelwerte"
    ' calculating mean values in columns of Worksheets
    wsCount = newBook.Worksheets.Count
    For j = 2 To wsCount
        LastRow = firstSheet.Range("A" & Rows.Count).End(xlUp).Row + 1
        Set ws = newBook.Worksheets(j)
        firstSheet.Range("A" & LastRow).Value = ws.Name
        ColCount2 = ws.Columns.Count
        ws.Activate
        Lr = ws.Range("A" & Rows.Count).End(xlUp).Row - 1
        For k = 2 To ColCount2
            Set rngAv = ws.Range(ws.Cells(2, k), ws.Cells(Lr, k))
            rngAverage = Application.Average(rngAv)
            Cells(Lr + 2, k).Value = rngAverage
        Next k
        Set rngAv = Nothing
        Set ws = Nothing
    Next j
    Application.ScreenUpdating = True
    ' Mean Values of TCs for different Temperatures in firstSheet
End Sub
  • runtime error 13 if I use Application.Average

    Application.Average is late-bound and behaves like the worksheet function AVERAGE , ie by returning an error value when the result can't be evaluated. Because an error value can't be coerced into a Double , the assignment fails with a type mismatch error.

    You could capture the result into a Variant , check to see if it's an error value, then assign to a Double ; use the IsError function to do this:

     Dim avgResult As Variant avgResult = Application.Average(...) If Not IsError(avgResult) Then rngAverage = avgResult 'rngAverage is safe to use as a Double Else ' avgResult is a #VALUE! error. what now? End If
  • runtime error 1004 if I use Application.WorksheetFunction.Average

    That's because WorksheetFunction.Average is early-bound , and handles errors in a way that is idiomatic to VBA: instead of returning an Error value, it throws a run-time error, which can then be handled with a normal On Error statement and error-handling subroutine.

The Average function is returning/throwing an error because the input it's given is invalid or contains errors - ie if you used the AVERAGE worksheet function on that data, you wouldn't be getting a Double result either. Fix the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM