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
This article demonstrates how to add or remove a value in a regular drop down list based on a list […]
In this tutorial, I am going to show you how to add values to a drop down list programmatically in […]
This article demonstrates how to place values automatically to a table based on two conditions using a short macro. Cell […]
This tutorial shows you how to add a record to a particular worksheet based on a condition, the image above […]
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]
In this small tutorial, I am going to show you how to create basic data entry with a small amount […]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]
In this article I will demonstrate how to quickly change chart data range utilizing a combobox (drop-down list). The above […]
The image above shows a chart populated with data from an Excel defined Table. The worksheet contains event code that […]
What's on this page Press with left mouse button on a specific cell to hide/show entire column Where to put […]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]
In this blog post, I will demonstrate some VBA copying techniques that may be useful if you don't know the […]
I will in this article demonstrate a macro that automatically opens all workbooks in a folder and subfolders, one by […]
I will in this article demonstrate a macro that copies criteria from one Excel Table and applies them to another […]
This article demonstrates several VBA macros, they will save you time if you have lots of worksheets. The first macro […]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]
Question: hi all, thanks for the great formula/array formula. it works great. lately, i noticed that the array formula will […]
It can sometimes be helpful having a large cell value in a comment. You can then easily hover over cell […]
This article demonstrates a macro that inserts new worksheets based on names in a cell range. The cell range may […]
Save links to your favorite macros in a personal tab on the ribbon for easy access and become more productive. […]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]
In this article, I am going to demonstrate a simple workbook where you can create or delete projects and add […]
This article demonstrates a macro that returns cell references for cell ranges populated with values on a worksheet. Jinesh asks: […]
In this post I am going to demonstrate how to quickly apply a filter to a table. I am using […]
In this tutorial, I am going to demonstrate how to filter an ExcelĀ define Table through a VBA macro. How it […]
This article describes different ways to locate literal or hardcoded values in formulas. The image above shows the result from […]
This postĀ Find the longest/smallest consecutive sequence of a value has a few really big arrayĀ formulas. Today I would like to […]
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]
This article demonstrates event code combined with Conditional Formatting that highlights overlapping date ranges based on the selected date range. […]
This post describes how to add a new custom-built item to the shortcut menu in Excel,Ā when you press with right […]
The Quick Access Toolbar is located at the very top of your Excel window, I highly recommendĀ that you place your […]
Rahul asks: I want to know how to create a vlookup sheet, and when we enter a name in a […]
This article demonstrates a formula and a VBA macro that returns every n-th row from a given cell range. The […]
The image above demonstrates a macro linked to a button. Press with left mouse button on the button and the […]
If you try to copy multiple cell ranges on a worksheet that don't have the same number of rows or […]
Did you know that you can select all cells containing comments in the current sheet? Press F5, press with left […]
This article describes how to create an interactive chart, the user may press with left mouse button on a button […]
Today I would like to share with you these small event handler procedures that make it easier for you to […]
This article demonstrates how to automatically create log entries when a workbook opens or closes using event code. Column A […]
In this smaller example, column D (Category) has empty cells, shown in the picture above. If yourĀ column contains thousands of […]
Macros and custom functions are great, they can automate many tedious tasks. To have them available whenever you need them, […]
This article demonstrates macros that save worksheets to a single pdf file. What's on this webpage Export all worksheets in […]
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]
In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and […]
The following macro inserts a new sheet to your workbook and lists all Excel defined Tables and corresponding Table headers […]
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]
This article demonstrates how to move a shape, a black arrow in this case, however, you can use whatever shape […]
This article demonstrates a recursive LAMBDA function and a User Defined Function (UDF) that multiplies numbers in each row with […]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
This article explains how to set up a workbook so a macro is run every time you open the workbook. […]
In this tutorial I am going to explain how to: Create a combo box (form control) Filter unique values and […]
In this post I am going to demonstrate two things: How to populate a combobox based on column headers from […]
Excel defined Tables, introduced in Excel 2007, sort, filter and organize data any way you like. You can also format […]
This post demonstrates how to: Insert a button to your worksheet Assign a macro to the button Create a basic […]
This article demonstrates a macro that allows you to rearrange and distribute concatenated values across multiple rows in order to […]
In this post I am going to rearrange values from a list into unique columns. Before: After: The code Get […]
This article demonstrates how to run a VBA macro using a Drop Down list. The Drop Down list contains two […]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userformĀ appears when the […]
This post demonstrates a macro that automatically selects cell A1 on each sheet right before you close a workbook. The […]
This article explains how to hide a specific image in Excel using a shape as a button. If the user […]
This article demonstrates a macro and a formula that allows you to sort delimited data in a cell or cell […]
This article demonstrates how to sort a specific column in an Excel defined Table based on event code. The event […]
In this post I am going to show how to create a new sheet for each airplane using vba. The […]
This article demonstrates how the user can run a macro by press with left mouse button oning on a button, […]
This blog post describes how to insertĀ qualifers to make "text to columns" conversion easier. Example I copied a table from […]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]
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.
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!