查找单元格是否匹配另一个工作表和计数/求和实例

我一直在使用简单的Excel数组公式来计算表格中的某些值,但是现在在我的文档中有太多的公式,而且Excel的崩溃。

因此,我想创build一个可以完成相同任务的macros。 我想让代码执行以下操作:

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

并且如果Sheet2中相邻列中同一行中的单元格不是空白,

然后计算特定string出现在Sheet2列A中的所有实例

并将值2列放在Sheet 1中原始活动单元格的右侧。

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

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

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

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

如果这是TRUE,那么对所有实例“加1”

并将该值放在Sheet1中。

我相信这样做的最好方法是For Next Loop,但是根据我find的例子还没有能够执行任何成功的代码。

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

这被设置为运行你在表1的列A中select的所有单元格。
它在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