2016-12-12 3 views
2

私は3つの値の平均を計算するループマクロを持っています。まれに、3つの値がすべて空白になることがあるので、平均値が空白になるようにセルを残し、ループの次の繰り返しでマクロを実行する必要があります。すべての空白値の平均とエラー処理

私は以前はエラー処理をしていませんでしたので、それに接する最良の方法は不明です。ここに私のコードは次のとおりです。

Sub sumavg() 
     Dim i As Long, j As Long 
     With Worksheets("datasummary") 
      For i = 1 To .Range("A" & .Rows.Count).End(xlUp).Row Step 5 
       For j = 1 To 6 
        With .Rows(i + 2) 
         .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10)) 
        End With 
        With .Rows(i + 3) 
         .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10)) 
        End With 
       Next 
      Next 

     End With 
    End Sub 

Here is a screenshot of the data

+0

てみ 'エラーで再開Next' – nightcrawler23

+0

@ nightcrawler23私はそれを検討しています。エラーが実際には処理されないので、結果は予測できないかもしれないと心配しました。そして、その行はマクロの先頭に書かれているのでしょうか、それともループに書かれていますか? – shecodes

+1

@shecodesの場合、あなたは既に知っている1つのエラーをカバーしている "盲目的な"ものなので、On Error Resume Nextを回避しようとしています。それは良いことではない)。 _real_エラー処理により、 'Application'のオブジェクト関数を返すことができ、返された値に可能なエラーをラップする機能があります(私の答えを参照してください) – user3598756

答えて

1

あなたはApplicationオブジェクトのAverage()関数を呼び出すと、エラーであることに対して、その結果を確認することができます。

Sub sumavg() 
    Dim i As Long, j As Long 
    Dim res As Variant '<--| this will store the result of Application.Average() function 

    With Worksheets("datasummary") 
     For i = 1 To .Range("A" & .Rows.count).End(xlUp).row Step 5 
      For j = 1 To 6 
       With .Rows(i + 2) 
        res = Application.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10)) 
        If Not IsError(res) Then .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10)) 
       End With 
       With .Rows(i + 3) 
        res = Application.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10)) 
        If Not IsError(res) Then .Columns(19 + j).Value = Application.WorksheetFunction.Average(.Columns(j), .Columns(j + 5), .Columns(j + 10)) 
       End With 
      Next 
     Next 

    End With 
End Sub 
1

あなたがOn Error Resume Nextを試すか、単にあなたが平均化されている値にゼロを追加することができます。

Sub sumavg() 
    Dim i As Long, j As Long 
    With Worksheets("Sheet2") 
     For i = 1 To .Range("A" & .Rows.Count).End(xlUp).Row Step 5 
      For j = 1 To 6 
       With .Rows(i + 2) 
        .Columns(19 + j).Value = WorksheetFunction.Average(.Columns(j) + 0, .Columns(j + 5) + 0, .Columns(j + 10) + 0) 
       End With 
       With .Rows(i + 3) 
        .Columns(19 + j).Value = WorksheetFunction.Average(.Columns(j) + 0, .Columns(j + 5) + 0, .Columns(j + 10) + 0) 
       End With 
      Next 
     Next 

    End With 
End Sub 
+0

0を追加することはできません私は実際に0の値を持つ試行と、排除する必要のある試行(つまり空白)を区別できる必要があるからです。私は次に再開しようとします。 – shecodes

+0

「On Error Resume Next」が正常に動作しているようです。 – shecodes

+0

素晴らしい! BTWの 'On Error Resume Next'はサブルーチンの中に入ります。あなたのケースでは 'Sub sumavg()'の直後になる可能性があります。 – nightcrawler23

関連する問題