2016-02-19 90 views
-2

我有這個宏在一個工作表上完美運行,但現在它在第13行顯示一個錯誤。宏基本上找到任何標題下的任何標題「獨特的拉」開始,然後將它們加在一起。VBA宏錯誤

我在想這與ActiveSheet有關,但我似乎無法弄清楚。

 If UCase$(ActiveSheet.Cells(1, i).Value) Like "UNIQUE PULLS*" Then 
      iTotal = iTotal + ActiveSheet.Cells(n, i).Value 
       ' For each of these columns, take value and add to total sum 
     End If 

Run-time error '13': Type mismatch

+2

「顯示錯誤」 - 出現什麼錯誤?導致錯誤的源數據是什麼?當數據不會導致錯誤時,源數據是什麼樣的?如果你知道它在第13行,那麼爲什麼向我們展示你的其他代碼?清理代碼以向我們展示只運行到錯誤點的相關部分,記錄導致錯誤的數據以及錯誤本身的詳細信息。 –

+0

此外,我建議刪除['.Select'和'.Activate']的所有實例(http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros )這可能會導致頭痛。 – BruceWayne

+0

我已經更新了這個問題,只顯示了一小塊代碼,並且還顯示了錯誤信息 –

回答

0

試試這個:

If Trim(UCase$(ActiveSheet.Cells(1, i).Text)) Like "UNIQUE PULLS*" Then 
     iTotal = iTotal + ActiveSheet.Cells(n, i).Value2 
     ' For each of these columns, take value and add to total sum 
End If 

如果你在這一行收到錯誤 - >iTotal = iTotal + ActiveSheet.Cells(n, i).Value2

這也許是因爲ActiveSheet.Cells(n, i).Value2不是可以添加的數字,而是其他某種數據類型使用Debug.Print ActiveSheet.Cells(n, i).Value2進行檢查,您將在Immediate window

中得到您要添加的總數的輸出210
1

當單元格的值是不是一個數字你會得到這個錯誤。您可以添加的則IsNumeric檢查跳過無任何數字單元:

If UCase$(ActiveSheet.Cells(1, i).Value) Like "UNIQUE PULLS*" And IsNumeric(ActiveSheet.Cells(n, i).Value) Then 
    iTotal = iTotal + ActiveSheet.Cells(n, i).Value 
End If 
+0

或者,他可以使用。文本屬性的單元格獲取文本,如果它是一個數字,它顯然不會匹配 – newguy

+0

我只是嘗試了IsNumeric方法,並且它不再將每列中的值相加 –

+1

@RobDunn這表明您的'VBA'未指向包含數字的單元格。 – ARich