cell1
并且cell2
是范围对象,对于赋值语句,你需要做
Set cell1 = ...
和
Set cell2 = ...
此外,这个公式几乎可以肯定不会出现#REF!
错误。
Worksheets("Combine").Cells(LastRow + 2, 2).Formula = "=sum(cell1,cell2)"
尝试类似:
Worksheets("Combine").Cells(LastRow + 2, 2).Formula = "=sum(" & cell1.Address & "," & cell2.Address & ")"
额外的功劳:尝试标注范围对象而不是笨重的 workbook.range.cells 构造:
Dim rng as Range
With Worksheets("Combine")
Set rng = .Range(.Cells(1, 1), .Cells(LastRow, 1))
End With
然后做:
For Each cell in rng.Cells
'
'
Next
将它们放在一起,并添加一个检查以确保您的总和不会出错:
Option Explicit
Sub tsada()
Dim cell As Range, cell1 As Range, cell2 As Range, LastRow As Long
LastRow = Sheets("Combine").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
For Each cell In Worksheets("Combine").Range(Cells(1, 1), Cells(LastRow, 1))
If cell.Value = "B/ 1" Then
Set cell1 = cell.Cells(1, 2)
End If
If cell.Value = "B/ 2" Then
Set cell2 = cell.Cells(1, 2)
End If
Worksheets("Combine").Cells(LastRow + 2, 1) = "B total"
If Not cell1 Is Nothing And Not cell2 Is Nothing Then
Worksheets("Combine").Cells(LastRow + 2, 2).Formula = "=sum(" & cell1.Address &"," & cell2 & ")"
End If
'# you should probably clear out these variables for the next _
' iteration , but you may not need to, I don't know enough about _
' your sheet or what you're trying to do, so this part is up to you
Set cell1 = Nothing
Set cell2 = Nothing
Next
End Sub