2014-11-24 83 views
1

現在我正在嘗試爲特定的彩色單元格搜索excel電子表格。當excel找到一個與顏色匹配的單元格時,然後希望excel從該單元格中取出數字並將其乘以其正下方單元格的偏移量。完成後,我可以將它存儲在另一個變量中。一旦在紙上找到所有的彩色單元格,它就會將所有的產品相加,並將答案返回到另一個單元格。這裏是我現在的代碼:如何將變量指定的範圍乘以VBA中的偏移量?

Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean) 
Dim rCell As Range 

Dim sResult 
Dim lCol As Long 
Dim vResult 
lCol = rColor.Interior.ColorIndex 

If SUM = True Then 'If true then sum the colored Cells 
    For Each rCell In rRange 
     If rCell.Interior.ColorIndex = lCol Then 

      vResult = WorksheetFunction.SUM(rCell, vResult) 'Sums the rCell and adds to vResult 'then stores in vResult 

     End If 
    Next rCell 'Goes to next cell 
    Else 

    For Each rCell In rRange 
     If rCell.Interior.ColorIndex = lCol Then 

      oCell = Range("rCell").Offset(1, 0).Select 
      pResult = oCell * rCell 
      vResult = WorksheetFunction.SUM(pResult, vResult) 

     End If 
    Next rCell 
    End If 
    ColorFunction = vResult 
End Function 

現在我有我的真正的一半程序工作得很好。我不能讓程序的錯誤部分在VBA中工作。任何幫助將是偉大的!

+0

你能給出更多的信息,指出哪裏出了問題? – Captain 2014-11-24 13:18:45

回答

0

這是不正確的:

oCell = Range("rCell").Offset(1, 0).Select 

RCELL未命名的範圍,但範圍itselve。嘗試:

oCell = rCell.Offset(1, 0).Select 

此外,你不需要選擇範圍,但得到範圍值。所以這樣會更準確:

oCell = rCell.Offset(1, 0).Value