将数字添加到 Lrow 时,运行时 1004 对象范围工作表失败

Runtime 1004 Range of Object worksheet failed when adding numbers to Lrow

我正在尝试使用 Lrow 将公式写入列中。我发现公式可以 运行 没有问题,当它只与 Lrow 一起使用时,但我有 运行 时间错误 1004 对象工作表范围在 Lrow - 6 时失败。计算在 B 列中完成,而 A 列中有我想要取平均值的数据。 Col A 的数据从 A2A & Lrow 。有人可以指出为什么会产生错误消息以及如何解决它吗? 提前谢谢了!这是我的代码:

Sub Calculation()
Dim wb As Workbook: Set wb = Workbooks("A.xlsx")
Dim sh As Worksheet
Dim Lrow As Long

For Each sh In wb.Worksheets
Lrow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row

sh.Range("B8:B" & Lrow -6).Formula ="=(average(A2:A13)"&"+average(A3:A14))/2"  'Here in range Lrow - 6 give me this error

Next sh

End sub

试试这个:

Sub Calculation()
  Dim wb As Workbook: Set wb = Workbooks("A.xlsx")
  Dim sh As Worksheet
  Dim Lrow As Long

  For Each sh In wb.Worksheets
    Lrow = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row
    
    If Lrow > 6 then
      sh.Range("B8:B" & Lrow -6).Formula ="=average(A2:A13)"&"+average(A3:A14))/2"
    Else
      Msgbox("There were less than 6 rows", vbExclamation)
    End if

  Next sh

End sub

如果你想让它运行无人陪伴并跳过没有足够行的表格,只需从上面的代码中省略这两行:

    Else
      Msgbox("There were less than 6 rows", vbExclamation)