Excel VBA - Paste into Find Command - vba

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.

Related

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

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(.....)

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.

Find a cell with Today's date in C4:V4 and paste content into cells below

I'm trying to figure out how to write a code that would :
copy contents of Array A,
look into Array B at the headers with dates,
find current date
and paste the contents directly beneath that cell.
So far the best I managed to achieve was have a macro find the date if I typed today's date specifically.
Edit: I was trying to repurpose a record macro and while the first time I recorded the same macro it worked, the next times it didn't all of sudden.
Sub Macro1()
Dim myDate As String
myDate = Format(Date, DDMMYYY)
Range("A5:A11").Select
Selection.Copy
Range("Table29[[#Headers],[23/01/2017]:[11/02/2017]]").Select
Selection.Find(What:="25/01/2017", After:=ActiveCell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Range(ActiveCell.Offset(1, 0), ActiveCell.Offset(7, 0)).Select
ActiveSheet.Paste
End Sub
Also I'm not sure but I feel like I was lacking some reference to activate Date function in VBA because whenever I try to use it I keep getting errors, even when I try to replicate other codes I found on google with Date in them.
Edit 2: I managed to get as far as paste stuff into desired array, but I still struggle to make Date work. If I don't manually type in the date, it won't work.

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?

Run an Excel VBA script on only the active worksheet and not the entire book?

I am using a VBA script to essentially find/replace. Right now when I run the VBA script it applies to all open sheets in the workbook. I wish for the VBA script to only apply in the active sheet and not touch the rest.
Here is my current macro code:
Sub ReplaceCC()
'
' ReplaceCC Macro
' Add CC to Distributor, Reseller, Government and Retail.
'
'
Range("A1").Select
Cells.Replace What:="Distributor", Replacement:="DistributorCC", LookAt:= _
xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="Reseller", Replacement:="ResellerCC", LookAt:=xlPart _
, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="Government", Replacement:="GovernmentCC", LookAt:= _
xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="Retail", Replacement:="RetailCC", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
Here is the entire VBA script with all subs.
I got the same problem. It depends of the Find/Replace history: if in the previous manual use of Find/Replace, you specified "Options > Search in Workbook", your macro will apply to all sheets. Otherwise, with the default "In Sheet", the macro will stay in the original Worksheet. I still don't know how to fix that from within the macro, though.
Interesting question. I believe that you could do what you're trying to do by simply placing "ActiveSheet" before each object reference in your code.
For example: Instead of Range("A1").Select use ActiveSheet.Range("A1").select
If you set up your code like this, whenever you execute, it should carry out its actions on the worksheet you currently have active.
EDIT: You should check to see which module you have this code placed in. If it is in an inserted module, I think you should be fine. On the other hand, if you've inserted it in one of the sheet modules it will only modify the sheet it is attached to. If you insert ActiveSheet before your cell references and the rest it will still modify the active sheet instead of the sheet the code is attached to.
It seems the macro was not recognizing the active sheet properly since the sheets were copies of each other. If you copy the content on Sheet 1 and create a new sheet then paste the content on it this will work. Each sheet needed to be unique and not just a copy of the original.
This is due to a VBA bug. When you use "Find" in VBA, the parameter "LookAt:=xlPart" or "LookAt:=xlWhole" works as expected. But when you use "Replace", the coded parameter is ignored and the replace uses the last MANUAL setting for its scope. The workaround is to do a "Find" operation right before the "Replace" operation, since "Find" uses the coded "LookAt" scope (thereby making the "Find"'s scope the last setting used, so the "Replace" will then use the scope coded into the "Find").
Solution from http://www.vbaexpress.com/forum/showthread.php?11444-Solved-Replace-in-a-sheet-and-not-the-entire-workbook
Dim dummy As Range
Set dummy = Worksheets(1).Range("A1:A1").Find("Dummy", LookIn:=xlValues)
Then you can post REPLACE functions underneath these lines of codes