查找If单元格在另一个工作表中的匹配并计数/求和实例



我一直在使用简单的excel数组公式来计算母表上的某些值,但现在在我的文档中有太多公式,excel崩溃了。

因此,我想创建一个可以执行相同任务的宏。我想让代码做以下事情:

如果Sheet1中的活动单元格与Sheet2中的列(或区域)中的任何单元格匹配,

AND如果Sheet2中相邻列中同一行中的单元格不为空,则

THEN计算特定字符串出现在Sheet2列A中的所有实例

并将值放置在Sheet1中原始活动单元格的右侧2列处。

这里是我使用的原始数组公式:

=SUM(IF(Sheet1!$A8=Sheet2!$A:$A,IF(SalesF_SignUp_data!$C:$C>1,1,0)))

上面的公式取Sheet1中的单元格A8,并检查它是否与Sheet2 column A中的任何单元格匹配,

并确保Sheet2中的C列在同一行中不是空白。

如果为TRUE,则为所有实例"add 1"

并将该值放在Sheet1中。

我认为最好的方法是For Next循环,但是根据我发现的例子,还没有能够执行任何成功的代码。

如果需要的话,我很乐意进一步解释。由于我没有10的声誉,我不能附加图像,但如果需要的话,我愿意发送。

设置为在工作表1的A列中选择的所有单元格运行。
它在Sheet2列A中查找Sheet1列A上的值,然后在Sheet1列B中显示该值在Sheet2列A中出现的次数以及在C列同一行中的值。如果答案是有帮助的,请这样标记。: -)

Option Explicit
Sub countinstances()
Dim result, counter, loopcount, tocomplete, completed As Integer
Dim findtext As Variant
Dim cell, foundcell, nextcell As Range
'Checks to make sure the sub isn't accidentally run on an invalid range
If ActiveSheet.Name <> "Sheet1" Or ActiveCell.Column <> 1 Or Selection.Columns.Count > 1 Then
    MsgBox ("Please select a range in column A of Sheet 1.")
    Exit Sub
End If
'In case of selecting the entire column A, curtail the number of blank cells it runs on.
tocomplete = Application.WorksheetFunction.CountA(Selection)
completed = 0
'For each cell in the selected range, searches Sheet2, Column A for the value in the selected cell
For Each cell In Selection
    If completed = tocomplete Then Exit Sub
    If cell.Value <> "" Then completed = completed + 1
    findtext = cell.Value
    result = 0
    Set foundcell = Sheets("Sheet2").Range("A1")
'Uses the count function to determine how many instances of the target value to search for and check
    loopcount = Application.WorksheetFunction.CountIf(Sheets("Sheet2").Range("A:A"), findtext)
'Skips the loop if the target value doesn't exist in column A
    If loopcount = 0 Then GoTo NotFound
'For each time the target value was found, check the cell in column C. If it's not blank, increment "result"
    For counter = 1 To loopcount
        Set nextcell = Sheets("Sheet2").Range("A:A").Find(what:=findtext, lookat:=xlWhole, after:=foundcell)
        If nextcell.Offset(0, 2).Value <> "" Then
            result = result + 1
        End If
        Set foundcell = nextcell
    Next
'Put the result in column B of Sheet1
NotFound:
    cell.Offset(0, 1).Value = result
Blanks:
Next
End Sub

最新更新