2013-10-06 48 views
0

我想要做一個列B的總和,它包含位於A列的2個項目「B/1」和「B/2」。我不確定是否我已經正確地定義了它,因爲它沒有進行公式化,它給了我運行時錯誤'91'。預先感謝您的意見。無法總結並給出了運行時錯誤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 
+0

我看到一些潛在的問題。什麼行引發錯誤? –

+0

@DavidZemens this line cell1 = cell.Cells(1,2) – user1204868

+1

'cell1'''cell2' are range objects,you need to do'Set cell1 = ...'and'Set cell2 = ...' –

回答

2

cell1cell2的範圍對象,賦值語句,你需要做的

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 
+0

,它給了我同樣的錯誤 工作表(「合併」)。Cells(LastRow + 2,2).Formula =「= sum(」&cell1.Address &「,」&cell2.Address&「)」 – user1204868

+0

如果'cell1'或'cell2'中的任一個未被分配,您還會期望發生什麼?你在一個條件('If')塊中對這些變量進行賦值。如果其中一個或兩個條件不計算爲「真」,那麼您有一個未分配的對象變量,因此「91對象,變量或帶塊未設置」錯誤。 –

+2

有關處理此問題的一種方法,請參閱上面對我的回答的修訂。我不知道你是否需要清除'cell1'和'cell2'變量,但我懷疑你可能會這樣做,所以我把這些行放在代碼中。如有必要,您可以將其刪除,以滿足您的需求。 –