2015-09-21 192 views
1

是否有任何方法將單元格的位置添加到SUM公式中?將單元格的位置添加到SUM公式中

我有以下For Each ... Next循環,而不是隻計算包含值爲1的單元格的數量,我想將這種單元格的特定位置添加到SUM公式中。

Dim rng As Range, cell As Range 
Set rng = Range("I3:DC70") 

For Each cell In rng 
    If cell.Value = 1 Then Range("DF4").Value = Range("DF4").Value + 1 
Next cell 

這可能嗎?

+1

你不使用COUNTIF得到相同的結果? – Davesexcel

+0

這是我在VBA的第一個項目,所以我不知道。我會檢查它。謝謝! – AOlson

+0

我測試了它,它確實給了我相同的結果,但我需要項目中另一個圖層的每個單元的具體位置。 – AOlson

回答

0

您將不得不使用.Find.FindNext。你可以閱讀關於它Here。這種方法比擁有大型數據集時循環要快得多。

這是我寫得很快的東西。請修改它以適應您的需求。

Sub Find_Cells_Which_Has_My_Damn_String() 
    Dim WhatToFind As String 
    Dim aCell As Range, bCell As Range 
    Dim SearchRange As Range, rng As Range 
    Dim ws As Worksheet 

    '~~> Set this to the relevant worksheet 
    Set ws = ThisWorkbook.Sheets("Sheet1") 

    '~~> Set here what to find 
    WhatToFind = "1" 

    '~~> Set this to the relevant range 
    Set SearchRange = ws.Cells 

    Set aCell = SearchRange.Find(What:=WhatToFind, LookIn:=xlValues, _ 
       LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
       MatchCase:=False, SearchFormat:=False) 

    If Not aCell Is Nothing Then 
     Set bCell = aCell 
     Set rng = aCell 
     Do 
      Set aCell = SearchRange.FindNext(After:=aCell) 

      If Not aCell Is Nothing Then 
       If aCell.Address = bCell.Address Then Exit Do 
       Set rng = Union(rng, aCell) 
      Else 
       Exit Do 
      End If 
     Loop 
    End If 

    If Not rng Is Nothing Then MsgBox rng.Address Else _ 
    MsgBox "No cells were found containing " & WhatToFind 
End Sub 

截圖

enter image description here

相關問題