我想使用 VBA 在 Excel 中自动执行此功能。
从 D1 获取值 (np. taks-223)
搜索工作簿,检查 D1 中的数据(现在手动 CTRL+F -> options{within: woorkbook} -> Find All)
我是否可以使用 Makro 或其他方式执行此功能?我最近一直在使用excel,还没有找到答案。谢谢 :)
使用上面列出的确切步骤录制宏不会为您提供任何可查看的代码,因为“查找全部”不会产生任何代码。但是,您可以使用代码构建一个公式来满足您的需求,然后将该公式写入 $H$1。这是包含 3 张工作表的工作簿示例。Sheet1 是您的搜索值所在的位置,而其他 2 张工作表的搜索值随机分散在各处。假设您不想在计数中包含单元格 D1,您可能会执行以下操作:
Sub countValueInWorkbook()
Dim formulaString As String
'//If you put your formula in any cell of Row 1, you will have a circular reference.
'//Start your formula with the sheet the search value cell is on, and count rows 2 thru 500 (or something)
formulaString = "=SUM(COUNTIF(Sheet1!2:500, $D$1),"
For Each wksht In ThisWorkbook.Sheets
If wksht.Name <> "Sheet1" Then
formulaString = formulaString & "COUNTIF(" & wksht.Name & "!1:500, $D$1),"
End If
Next wksht
'//Trim trailing comma and add ending parenthesis
formulaString = Left(formulaString, Len(formulaString) - 1)
formulaString = formulaString & ")"
'//Write formula to desired cell
Sheets("Sheet1").Range("$H$1").Value = formulaString
End Sub
使用与此类似的方法,您将能够计算工作簿每个工作表中搜索值的所有实例。如果要在计数中包含搜索值单元格本身,请更改以下行:
formulaString = formulaString & ")"
至
formulaString = formulaString & ", 1)"
以便 SUM 将添加额外的 1。
运行此代码后,我在单元格 H1 中得到以下公式:
=SUM(COUNTIF(Sheet1!2:500, $D$1),COUNTIF(Sheet2!1:500, $D$1),COUNTIF(Sheet3!1:500, $D$1))
希望这对你有帮助!
编辑以显示使用搜索单元格本身而不是静态值,以便当您更改 D1 中的内容时,H1 中的公式会更新以计算新值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句