0

我正在尝试对位于 A 列的包含 2 个项目“B/1”和“B/2”的 B 列求和。我不确定我是否正确定义了它,因为它没有做制定总和,它给了我运行时错误'91'。预先感谢您的意见。

我的代码:

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 
cell1 = cell.Cells(1, 2)
End If

If cell.Value = "B/ 2" Then 
cell2 = cell.Cells(1, 2)
End If

Worksheets("Combine").Cells(LastRow + 2, 1) = "B total"
Worksheets("Combine").Cells(LastRow + 2, 2).Formula = "=sum(cell1,cell2)"
Next

End Sub
4

1 回答 1

2

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
于 2013-10-06T03:50:17.803 回答