VBA script in excel to find and highlight text - vba

I am looking for a VBA script that will help me find certain keywords in a cell and if found highlight the entire row. Below are my requirements:
I have a database of words eg hell, get out, shut up, don't you dare etc. I need a macro to search the data in column "E" of excel and in case any of the cell in column "E" contains any word listed in the database (irrespective of the case of the word upper or lower)the entire row is highlighted. The word can be in the beginning, middle or end of the cell and the macro should be able to find that word and highlight the column.
Seeking help from all VBA masters for this.

You can do this with conditional formatting, instead of VBA.
Conditional formatting works by applying a 'second formula' to a given cell. If the 'second formula' results in TRUE, then special formatting conditions can be applied.
EXAMPLE CONDITIONAL FORMATTING
For example, if you have a single column of Data, A:A, and you want to check if that column has the exact string "hello world", you could add a conditional format [Home ribbon, Styles section, Conditional Formatting] that turns a cell yellow with this formula:
=$A1="hello world"
This will only result in TRUE if the cell in column A at that row equals exactly "hello world" [note that Column A has an absolute-reference $, and row 1 does not, so row 1 is relative to the position of the cell in the condiitonal format rule].
To check to see if any row in column A includes hellow world, we need to add a SEARCH function, which checks to see if a small search string is inside of a larger string:
=SEARCH("hello world",$A1)>0
Because SEARCH by default returns the first character in a larger string that matches the search term (and if it finds nothing, it returns #N/A), we check to see if our search for "hello world" in column A returns a number.
SEARCHING MULTIPLE COLUMNS
Now, to see if ANY column, say from A-D, includes "hello world", we concatenate each value of each column so that it gives us a single string, which we can search through for "hello world", like so:
=SEARCH("hello world",$A1&$B1&$C1&$D1)>0
This will first create a single string, equal to A1 & B1 & C1 & D1 all in a row. Then it will search that newly created string to see if "hello world" is inside it, and return a number value if it is.
ARRAY FORMULA BASICS
Finally, we need to do the tricky part - searching for multiple terms instead of just "hello world". This is called an Array Formula. An array formula works by performing a single operation on multiple cells, and then returning multiple results in an Array. In an Excel sheet, an array formula must be confirmed with CTRL + SHIFT + ENTER (instead of just ENTER), but in conditional formatting, you actually don't need to do anything special - it will recognize an array formula without a special command.
As an example of conditional formatting, see this example, which checks whether any value from A1:A5 = 10, and if it does, it gives us the value in B1:B5:
=IF(A1:A5=10,B1:B5,"")
Remember in Excel on a worksheet, this would be confirmed by pressing CTRL + SHIFT + ENTER. If you do test this, it will give you the following result, assuming A2 = 10 and A5 = 10:
={"";B2;"";"";B5}
This result would actually be hidden, because Excel can't "collapse" an array function on its own. So assume column B had values, and we actually want to sum them together. We would then wrap the Array formula in a SUM function:
=SUM(IF(A1:A5=10,B1:B5,""))
As you can see if you test this, we have actually created our own SUMIF function, using Array formulas instead of the built-in SUMIF.
SEARCHING FOR MULTIPLE TERMS WITH ARRAY FORMULAS
So now we apply these principles to the conditional formatting, to create an array formula which will check our concatenated 'NEW STRING' for any number of provided terms, as follow [Assumes the search terms are typed into cells E1:E10]:
=SUM(SEARCH($E$1:$E$10,$A1&$B1&$C1&$D1)>0)
This formula can be placed as a conditional formatting rule which reaches all of A:D. Set the rule to highlight / change format in whatever way you like.

Related

INDEX & MATCH instead VLOOKUP

I have 2 validation lists, both have numbers & texts amongst them (but none of the lists have alpha-numeric symbols). They are on another sheet called "Source".
I'm using the statement of:
=INDEX(Sources!$A$3:$A$32,MATCH(LEFT(Sources!$A$3:$A$32,3)&"*",Sources!$B$3:$B$42,0)).
But I keep getting #N/A. Can anyone help?
You will not be able to lookup a range within another range using MATCH formula. In your formula you are using match to lookup A3:A32 within B3:B42. Ideally the match formula can lookup only 1 value in B3:B42 and not the complete range of values.
Your formula should be,
=INDEX(Sources!$A$3:$A$32,MATCH(LEFT(Sources!$A$3,3)&"*",Sources!$B$3:$B$42,0))
If you want to drag formula varying the A3 to A32 , use the below,
=INDEX(Sources!$A$3:$A$32,MATCH(LEFT(Sources!A3,3)&"*",Sources!$B$3:$B$42,0))
This type of lookup with range within a range works only on array formulas. Your formula seems much of array formula. After pasting the formula in formula bar, press ctrl + shift + enter . This will make your formula as an array formula. If you do not want to use that as an array formula, try my formulas with just enter

UDF to return formatted number

Sometimes I like to display numbers along with text in the same cell. To do this, I custom format the cell to something like 0.00" test", e.g. a cell A1 with formula =PI(), but formatted with custom format 0.00" test" would return a displayed result of 3.14 test.
Crucially, the value of the cell is unchanged by the formatting - you can still do =A1 * 3 in another cell and get the result - since the value of A1 is still Pi, only it's display has changed.
For a UDF that returns a numerical value (in my case, Long, but it could be any number), is there a way of returning a cell such that it is displayed 1 way, but it's actual value (.Value2 in VBA I believe) is a number, not text.
I've tried Format( in VBA, but it returns a text string. I would just format my cell how I want it manually, but as you can see from the below code, the formatting is dependent on intermediate results (I'm trying to return the value formatted with the time the calculation took).
UDF_RESULT = Format(valueResult.Length, IIf(tElapsed < timeout, "0" & " """ & Round(tElapsed, 2) & "s""", "0"))
This would be easy to do with a Macro, but within a UDF it's harder. I could declare all of the intermediate values at a module level, then a Worksheet_Calculate() macro can access those values and apply the custom formatting, but a UDF-wrapped approach would be much better.
No.
You're confusing a cell's value with its number format. A UDF can compute a value, and the cell is free to format that value as needed.
So if a UDF returns a number, the cell's value is the result of that function - a number.
Just format the cell as needed. A function doesn't format anything.

(Excel VBA) - Draw from cell text in a macro

I'm trying to build a small macro that allows the user to format multiple different documents at once.
I would like for the user to be able to enter into a particular cell within the document containing the macro a particular piece of text.
I then want for this piece of text to be able to be drawn upon in the macro while affecting a different document.
For instance, a code to add another column might say
Worksheets(1).Range("A1").EntireColumn.Insert
Instead of specifying the column (A), I would like it to draw on a value in the host document. For instance, the user types "G" into the particular cell, and then clicks a button to run the macro, and the macro will dynamically know to affect column G in all excel documents it targets based off of the value in the host document.
I hope this makes sense.
Any suggestions for the sort of functions I should be looking at to make this work?
"Any suggestions on the sort of functions I should be looking at?"
Here's a few...
To get the value which is entered...
If the cell will always be in the same address, say A1:
' Define a string variable and set it equal to value in A1
Dim cellText as String
cellText = ThisWorkbook.ActiveSheet.Range("A1").Value
or instead of using Range you can also use Cells which takes a row and column number.
cellText = ThisWorkbook.ActiveSheet.Cells(1, 1).Value
If the cell changes then you may need to look into the Find function to look for a label/heading next to the input cell. Then you can use it (easily with Cells) to reference the input...
Once you have this variable, you can do what you like with it.
To put this value into cell B3 in another (open) workbook named "MyWorkbook", and a sheet named "MySheet" you can do:
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range("B3").Value = cellText
To insert a column at cellText, do
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range(cellText & "1").EntireColumn.Insert
Notably here, the & concatonates the strings together, so if
cellText="B"
then
cellText & "1" = "B1"
Further to your comment about moving values between sheets, see my first example here, but always refer to the same workbook. If you find yourself repeatedly typing something like
ThisWorkbook.Sheets("MySheet").<other stuff>
then you can use the With shorthand.
With ThisWorkbook.Sheets("MySheet")
' Starting anything with a dot "." now assumes the with statement first
.Range("A1").Value = .Range("A2").Value
.Range("B1").Value = .Range("B2").Value
End With
Important to note is that this code has no data validation to check the cell's value before using it! Simply trying to insert a column based on a value which could be anything is sure to make the macro crash within its first real world use!

If content in a cell is too long, show "Multiple" instead of letting the text overflow in Excel

So, I have a custom function that concatenate different cells and put a comma between words.
For example, say I have "ABCD" "BC" then, this function will
output ABCD, BC. Now the problem is that the text will overflow in a cell and overlap with the cell next to that. In order to solve this problem,
I am thinking of just replacing the concatenated word with "Multiple" if more than 3 words are combined. Is there anyway to do this in a cell?
You can do this with conditional formatting AND keep the original underlying string as a raw value for other purposes.
Select the cells with the formula and create a conditional formatting rule based on a formula.         =LEN(C2)-LEN(SUBSTITUTE(C2, ",", ""))>1 
Click Format and go to the Numbers tab. Choose Custom from the list down the left side and supply the following for the Type:         ;;;[color13]_((\multipl\e)   I've opted to also make the font dark blue (colorindex # 13) and indent from the left.
Click OK to accept the formatting and then OK again to create the new rule.
        
As you can see in the sample image above, the underlying raw value remains (shown in the formula bar) but (multiple) is displayed.
More on custom number formatting codes at Number format codes

Major formatting issue in Excel - VLOOKUP

I need help with a formatting issue in Excel, which is interfering with the VLOOKUP function in my Excel sheet.
I have two sheets with more than 20,000 column values as lookup, and the same number of values for reference. All the values in both cells are weirdly formatted, some with green triangles at the upper left corner of cells, some are text, etc.
Is there a way in Excel using a macro/VBA to remove or make all formatting similar in both sheets? The reason for VBA is because the person who is going to work with this file needs everything automated and is not familiar with Excel at all. I already have the VLOOKUP function in the cells, I just need to work with the formatting.
Well, I fight with partial lookups this way:
In the items array, I create new empty FIRST column and then place formula
="+"&B2
This will take the content of Cell B2 and add + in the front of it.
When I do vlookup, I add "+" to searcheable value
=VLOOKUP("+"&A6,A:O,2,FALSE)
Therefore, instead of comparing for example Strings and numbers, I compare Strings, by adding "+" in the front.
Another technique, is to kill all formatting:
Select whole column, click DATA-TEXT TO COLUMNS-DELIMITED and then DESELECT ALL DELIMITERS. Click Finish. This will clear your formatting.
===========================================================================
This is the VBA solution you asked for:
Call it from Excel
=GetLookup(G2,A:C)
Here is VBA:
Function GetLookup(LOOKFOR As String, RANGEARRAY As Range) As String
GetLookup = Application.WorksheetFunction.VLookup("+" & LOOKFOR, RANGEARRAY, 3, False)
End Function
Good luck!
I'm assuming the data type in all of the cells is the same, or you want it to all be the same. The following steps will make the cells a uniform type:
Save your workbook, in case this does not do as you require
Select all cells you wish to be of the same cell type
Press Ctrl+1, on the "Number" tab, select the type you wish these cells to take. Press OK.
Open the VBA editor using Alt+F11
Open the immediate window with Ctrl+G
Type the following: for each cell in selection : cell.formula = cell.value : next cell
Press enter (you may have to wait a few seconds).
If you take this action with the same data type (e.g. choose "Text" for both ranges in step 3) on both your ranges you should be "comparing apples with apples" and your VLOOKUP should function as required.
Hope this helps.
Edit: formatting, clarification