Count text string in all formulas in a worksheet [VBA]
I will in this article demonstrate a macro that counts how many times a specific text string is found in cells containing formulas.
Press with left mouse button on button named "Start" to run the macro named "CountTextInFormulas". The macro will use the value in cell C2 to count how many times that particular string is found in a worksheet. The result is shown in cell c3.
In the example above, the macro counts how many times the text string "COUNTIF(" is found on the current worksheet. 18 is the result. There are 18 formulas in cell range F7:F24 containing text string "COUNTIF(".
Note that this macro counts all matching text string in a cell, in other words, if the text string is found three times in one cell the macro returns 3 for that cell and then returns the total to cell C3.
I will also in this article demonstrate how to
- create a button and place it on a worksheet.
- assign a macro to a button.
- where to put the VBA code.
- how to save your workbook as a macro-enabled workbook.
- explain how the macro works.
I have many excel files with multiple sheets and each excel sheet has many formula which are starting from particular word e.g. FDS, FDSB, etc. Some formula has FDS, FDSB occur in the middle of the formula.
Below is the formulae for your referance
=IFERROR(FDSB($D21, "IC_ESTIMATE_DATE(ALL, EXP_RPT,QTR, 3, 0, , , 'MM/DD/YYYY')@RC_ESTIMATE_DATE(ALL, EXP_RPT, QTR, +3, 0, , , 'MM/DD/YYYY')"), "na")
I need to find out how many times FDS,FDSB has been appear in the sheet(total count) in such a way there are many formulas in all the cells
I just need to count the how many times FDSB occur in one particular worksheet
VBA Code
I wanted to quickly select all cells containing formulas on a sheet. I found Rick Rothstein (MVP - Excel) macro here and modified it.
'Name macro Sub CountTextInFormulas() 'Dimension variables and declare data types Dim Rng As Range, C As Range, Cnt As Double, Scnt As Double 'Enable error handling On Error Resume Next 'Save a reference to cells containing formulas to range object named Rng Set Rng = Cells.SpecialCells(xlFormulas) 'Disable error handling On Error GoTo 0 'Check if Rng is not empty If Not (Rng Is Nothing) Then 'Iterate through each cell in range object Rng For Each C In Rng 'The With ... End With statement allows you to write shorter code by referring to an object only once instead of using it with each property. With Worksheets("Sheet1") 'Calculate how many times the text strign is found in a given cell Cnt = (Len(C.Formula) - Len(Replace(C.Formula, .Range("C2"), ""))) / Len(.Range("C2")) End With 'Add number to count variable Scnt = Scnt + Cnt 'Continue with next cell Next End If 'Return number to cell C3 on worksheet Sheet1 Worksheets("Sheet1").Range("C3").Value = Scnt End Sub
Where to put the code?
- Press shortcut keys Alt + F11 to open the Visual Basic Editor.
- Press with left mouse button on "Insert" on the menu.
- Press with left mouse button on "Module".
- Paste code to module window.
- Exit VB Editor and return to Excel.
Create button
- Go to tab "Developer" on the ribbon. You have to enable the "Developer" tab if it is missing.
- Press with left mouse button on "Insert Controls" button.
- Insert a button (Form Controls) on the sheet near cell C2.
- Select a macro to assign a macro to your button.
- Press with left mouse button on OK to close the dialog box.
Edit text in button
- Press with right mouse button on on button.
- Press with mouse on "Edit text"
- A prompt appears inside the button. Clear the text and then type what you want it to say.
- Press with left mouse button on somewhere outside the button to save the text you wrote.
Change button size
It is hard to select the button if a macro is assigned to it. Use the right mouse button to select without triggering the macro. The image above shows sizing handles around the button.
- Press with right mouse button on on the button to select it. You know it is selected when the sizing handles appear.
- Press and hold with the left mouse button on any of the size handles.
- Drag with mouse to change the size.
- Release the mouse button when you are happy with the button size.
You can use the SHIFT key to resize the button keeping the relationship between width and height. This works only if you press with left mouse button on and drag the corner handles.
The Alt key lets you snap to the cell grid while resizing the button, the animated image above shows this.
Change button location
- Select the button.
- Press and hold with left mouse button on the button.
- Drag with mouse to the desired location.
You can press and hold the SHIFT key to move the button vertically or horizontally using the mouse.
The Alt key lets you snap the button to the cell grid beneath.
Macro category
Table of Contents Add values to a regular drop-down list programmatically How to insert a regular drop-down list Add values […]
This article demonstrates how to place values automatically to a table based on two conditions using a short macro. Cell […]
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
Excel categories
4 Responses to “Count text string in all formulas in a worksheet [VBA]”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
Contact Oscar
You can contact me through this contact form
I have some comments about your macro's code...
1) You declate a clen variable and set it in the first line of code inside the For..Next loop, but then you never use it afterwards.
2) All the variable you declared as Single will be whole numbers, so I think declaring them as Long would be more appropriate.
3) You protected the call to SpecialCells from erroring out if the worksheet has no formulas on it; however, the For statement will error out if the Rng variable is Nothing (which would be the case when the sheet has no formulas on it).
Below is shorter macro which (untested claim) should execute faster than the code you posted..
I presume you chose to implement your code as a macro rather than as UDF (user defined function) because your code makes use of the SpecialCells function which, for whatever reason, Microsoft chose to exclude its use within UDFs. However, the approach my code uses does not have such a restriction, so it can be converted into a UDF quite easily...
So, instead of maintaining a button and having to press it whenever you change the text being counted OR number of formulas on the sheet, you can just have this formula (which uses C2 for the text string to count... a quoted text string could be used as well) which should update automatically...
=FCount(C2)
Note that, for the UDF, I also provided the ability to perform a case sensitive or case insensitive search (should the user want to count, say, text strings within quoted text inside of formulas only) via an optional second argument. The default (if this second argument is omitted) is FALSE which performs a case insensitive search; specifying TRUE (or then number 1 if you prefer short formulas) will performa a case sensitive search...
=FCount(C2,TRUE)
Rick Rothstein (MVP - Excel),
1, Corrected!
2, Well, there can´t be anything else than whole numbers? What if the macro returned 0.5, what does that mean? The text string was found partially?
3, Corrected!
I presume you chose to implement your code as a macro rather than as UDF (user defined function) because your code makes use of the SpecialCells function which, for whatever reason, Microsoft chose to exclude its use within UDFs. However, the approach my code uses does not have such a restriction, so it can be converted into a UDF quite easily...
You are right!
Both the subroutine and the function work, many thanks for sharing!
With respect to your response #2:
This line of code...
can only assign whole number values to the Cnt variable. The subtraction part will always leave an exact multiple of the length of the text in cell C2 (since that is how many character the Replace function removed... the multiple number of times the text in cell C2 occurred in the original text), so that when you divide it by the length of the text in cell C2, the result must always be a whole number value... fractional results can never result from the calculation. Hence, it would be more appropriate to declare Cnt as a Long instead of a Single. And, since the Scnt variable is calculated by adding all of these resulting Cnt values, it too can only contain whole number values, so would be more appropriate for it to be declared as a Long instead of a Single as well.
Rick Rothstein (MVP - Excel),
Thanks for explaining!