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
我看到一些潛在的問題。什麼行引發錯誤? –
@DavidZemens this line cell1 = cell.Cells(1,2) – user1204868
'cell1'''cell2' are range objects,you need to do'Set cell1 = ...'and'Set cell2 = ...' –