简体   繁体   中英

VBA Excel find and counts

I would like to automate this functionality in Excel using VBA.

  1. Gets the value from D1 (np. taks-223)

  2. Searches the workbook, check data from D1 (now manually CTRL+F -> options{within: woorkbook} -> Find All)

  3. Counts how many times the data in the workbook has appeared, writes the result to cell H1

Will I be able to do this functionality with Makro or otherwise? I have been using excel recently and have not found an answer yet. Thank you :)

Recording a macro with the exact steps you list above will not give you any code to look at, as "Find All" doesn't produce any. However, you can use code to construct a formula that will give you what you want, and write that formula into $H$1. Here's an example of a workbook with 3 sheets. Sheet1 is where your search value is, and the other 2 sheets have the search value randomly scattered throughout. Assuming you don't want to include cell D1 in the count you might do something like:

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

Using something similar to this, you will be able to count all instances of the search value in every sheet of the workbook. If you want to include the search value cell itself in the count, change the following line:

    formulaString = formulaString & ")"

to

    formulaString = formulaString & ", 1)"

so that the SUM will add the additional 1.

After this code is run, I end up with the following formula in cell H1:

=SUM(COUNTIF(Sheet1!2:500, $D$1),COUNTIF(Sheet2!1:500, $D$1),COUNTIF(Sheet3!1:500, $D$1))

Hopefully this helps you!

Edited to show using the search cell itself instead of static value so that when you change what's in D1, the formula in H1 updates to count the new value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM