代码用平均值替换多个工作表中的空白

时间:2018-10-29 11:01:02

标签: excel

嗨,我有这段代码,可以用平均代码替换我的工作表中的空白,我需要用它来遍历大多数工作表,但它不能运行全部,目前只执行1次。

Sub FillBlanks()

Dim ws As Worksheet
    For Each ws In Worksheets


Dim rng1 As Range
Dim rng2 As Range

             Set rng2 = Range("L1:AB40")

             On Error Resume Next
             Set rng1 = rng2.SpecialCells(xlBlanks)

                 Application.Iteration = True
                 rng1.FormulaR1C1 = "=AVERAGE(R[-1]C,R[1]C)"
                 Application.Iteration = False
                 rng2.Value = rng2.Value

    Next ws 
End Sub

我想知道这段代码缺少什么?

1 个答案:

答案 0 :(得分:0)

您需要告诉它工作表Range(“ L1:AB40”)在什么位置。

Set rng2 = ws.Range("L1:AB40")

如果没有空格,您还可以使用更好的错误控制。

Sub FillBlanks()

    Dim ws As Worksheet
    Dim rng1 As Range
    Dim rng2 As Range

    For Each ws In Worksheets

         Set rng2 = ws.Range("L1:AB40")

         On Error Resume Next
         Set rng1 = rng2.SpecialCells(xlBlanks)
         on error goto 0

        if not rng1 is nothing then

             Application.Iteration = True
             rng1.FormulaR1C1 = "=AVERAGE(R[-1]C,R[1]C)"
             Application.Iteration = False
             rng2.Value = rng2.Value

        end if

    Next ws 

End Sub