How to define 'Within' match criteria using VBA Find or Replace function? - vba

There are similar questions regarding this, but none address my issue.
I have a tool that is basically a bulk find/replace. I define a set 'template' of data with keyword placeholders in it, then provide a list of template instance definitions that define values for these placeholders, and the tool simply copies the template as many times as I have template instances, and find/replaces the placeholders as it goes.
The find/replace code uses:
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
For iParam = LBound(gsaXMLParams) To UBound(gsaXMLParams)
Selection.Replace What:=gsParamSymbol & gsaXMLParams(iParam) & gsParamSymbol, Replacement:=gsaXMLParamVals(iInstance, iParam), LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next
I only want to replace the current sheet. The trouble is, there is no 'Within' argument in the Replace function, and instead the replace function uses the currently set 'Within' criteria as set in the Excel Find/Replace tool. If this is set to 'Workbook', then all of my sheets have their cells replaced (if matching replace criteria).
I have tried using Range.Replace as well which produces the same issues.
How do I set the 'Within' criteria programmatically??
Example data:
E.g. Template:
|Area|.|SiteName|.Metering.Value
|Area|.|SiteName|.Enclosure.Door
E.g. Template Instance Definitions
Area SiteName
Area 1 John's Town
Area 2 Peter's Town
E.g. Output
Area 1.John's Town.Metering.Value
Area 2.Peter's Town.Metering.Value

The 'within' you are speaking of is the Range.Replace Method's parent.
When you use Range("A1").Font.Color = vbRed, you are setting the color of the font of A1 so Color is a Property of Font and Font is a Property of Range, specifically, Range("A1").
So if you use the Worksheets("Sheet1").Cells.Replace what:=..., replacememt:=..., method, you are performing it on the cells in Sheet1, and only those cells just as setting the font color in the earlier example only set a red font in A1. Currently you are making the replacement on whatever is selected.

Doing a little more Googling, there doesn't look like there's a 'proper' solution, however using the first line of the following before any Replace calls will reset the Find/Replace tool options, including resetting Within to 'Sheet':
Set r = Worksheets(1).Range("A1").Find(What:="This will reset the Find/Replace tool options, including setting Within=Sheet")
Range("A1:B10").Replace(.....)

Related

Finding function next value in a specific column

I am trying to make a macro button that will automatically select column H and then search and select one by one in an array(one every time I click the macro) every cell in that specific column, that contains the € symbol. I can do that exactly as I want manually using the native excel search function but it is time consuming. Yet I don't know how to do that in VBA. Note that the cells in column H are currency formatted..The code that almost works for me so far is this:
Search = InStr(ActiveCell.NumberFormat, Chr(128))
Selection.Find(What:=Search, After:=ActiveCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
BUT the above code doesn't automatically select column H for search. I have to do that manually. When i insert in the above code Columns("H").Select (in order to make the code select the column H automatically) the macro selects the first cell that contains the € symbol in the column H (which is what i want) BUT when clicking again it does not go to the NEXT cell that contains the € symbol in that column. It sticks on the first finding. Could you please help me?
You should always avoid using Selection. or .Select.
Instead of Selection.Find specify the correct range:
Worksheets("MySheetName").Columns("H").Find
Also have a look at the Range.FindNext Method (Excel). With find you will always find the first occurrence only. For further searches you will need to use FindNext.
I am not sure what do you want to achieve, but if you need to find cells formatted as Currency, I would rather use this code:
Sub findCur()
Dim rngCol As Range
Set rngCol = Range("H:H")
With Application.FindFormat
.Clear
.NumberFormat = "$#,##0.00"
End With
rngCol.Find(What:="*", After:=ActiveCell, SearchFormat:=True).Select
End Sub
Add a condition to the selection, something like:
If Selection.Column<>7 then Columns("H").select
This way if you are already in column H, it won't reselect it, but if you are not there, it will go there.

How to expand a group in Excel by using Hyperlink(or by maybe assigning Macro to Hyperlink)

I have a table at the top of my sheet and this table has a different section names.
I'd like to insert a hyperlink to these section names to go and open it's group below when I click them.
Please Refer to the view of my table and sections as default (Collapsed)
I could create a macro which:
Expands all groups
Goes to the Section that I clicked,
Collapses all groups
Only opens the group on active cell,
But assigning this macro to ~20 different sections increases the file size.
After some search I found this on SO: Excel: Assign a macro to a hyperlink? So maybe there is a way to connect this two method?
How this can be solved?
I'd suggest creating a master sheet with the "group" table and any rollups you need. The subsequent sheets could have all the "section" data on them. This has the added benefit of being more scaleable.
Is it strictly necessary to have all the information on the same sheet? This is pretty much why Excel has multiple sheets. Using multiple sheets would also allow you to use standard hyperlinks.
However, if you would like some VBA to get you closer, consider the code below. This grabs the value form the active cell, then searches for the next cell with that value. If the section with the found cell is collapsed, it expands it and visa versa.
Sub OpenSection()
Dim x As String
x = ActiveCell.Value
Dim y As String
y = Cells.Find(What:=(x), After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Address
'Range("b1").Value = y
With ActiveSheet
With .Range(y).EntireRow
If .ShowDetail = False Then
.ShowDetail = True
Else
.ShowDetail = False
End If
End With
End With
End Sub

Replace part of formula

my macro is deleting some spreadsheet (let's call it "Base") and replacing it with similar, same name and format, but with different data. There are formulas in other sheets which are refering to "Base" spreadsheet. This formulas, after execution of the macro, return #ADR! error, and formulas are changed, for example:
=SUM(Base!AA:AA)
becames:
=SUM(#ADR!AA:AA)
I want to replace "#ADR" with "Base" in every formula, to get rid of this error. One of apporaches which I have been trying is:
Selection.Replace What:="#ADR", Replacement:="Base", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
but it doesn't work, even though when I am trying to do it manualy, using Ctrl+h shortcut, everything is perfect.
How can I replace "#ADR!" with "Base" in every selected formula using a macro?
=SUM(INDIRECT("Base!AA:AA"))
INDIRECT takes a string argument, so you will not lose the reference when the sheet is deleted.
When you delete the sheet you delete that entity. Although you then create a new sheet with the same name it is not the same entity.
So when you delete the sheet, formulas in other sheets referencing it lose that reference. Creating a new sheet with same name will never fix the links.
Would it not be simpler to overwrite the data in the Base sheet, therefore preserving all the links and eliminating the issue entirely?

Excel VBA - Paste into Find Command

I'm trying to create a macro which searches for a string of text that has been entered/selected from another cell. When I record the macro, it sets the "What" part of the find function as the specific text that was copied when recording the macro, rather than a Paste Selection, which is what I want.
Sub GOTOSECTION() ' ' GOTOSECTION Macro '
'
Range("B7").Select
Selection.Copy
Cells.Find(What:="Section 4A", After:= _
ActiveCell, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
Cells.FindNext(After:=ActiveCell).Activate
End Sub
But I want the "What:" to be the value copied from cell B7. When I try to input a paste command in there it gives me a syntax error, so I'm sure it's something really basic I'm missing (I'm pretty green when it comes to vba, and I've been unable to find examples of what I'm looking for online).
Thanks for any input!
Replace What:="Section 4A" with What:=ActiveCell.Value
This will get the current value of the currently selected cell (though it might (though I'm not 100% sure without checking) cause some errors if the cell is blank, so consider error checking).
EDIT:
If you're continuing to use the macro recording in the future, it might be worth looking into relative references. I've never used it for anything like this, so I'm not sure if it will have an effect, but it could, so check it out.

Apply formatting to an Excel file programmatically

I want to format an existing Excel file (xls) cell in such a way that the cell values in a column only show two digits after the decimal.
So instead of 0.090919729581319146%, I want to show 0.09%.
I need to do this across multiple documents, so I need some repeatable way to apply the transformation. I was thinking of a macro - and tried it with the integrated macro recorder in Excel 2010, but unfortunately couldn't get it to work.
I have only to format a Range from C3 --> C5000.
I found something on web. Look at this code. It does what i am talking about:
Sub NurZumUeben()
With Range("C2:C5000")
.Replace What:="%", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows
Range ("K1") = 100
Range ("K1").Copy
.PasteSpecial Paste :=xlPasteAll, Operation:= xlDivide
.NumberFormat = "0.00%"
Range("K1").Clear
End With
End Sub