Excel VBA Find/Replace Macro - excel

Good Morning,
I am working with a rather large dataset and I am attempting to Find/Replace values which have been modified in one spreadsheet back into the original. What I would like to do is have the macro look for the information in Cell A1 and Replace it with the value in Cell B1, and then continue down until Cell A3600:B3600. Generally, I'm pretty good at peicemealing the code I find on here to get it to do what I want, but I'm at a loss as to what I should be looking for.
What I have right now is:
Sub Macro1()
'
' Macro1 Macro
'
'
Range("A1").Select
Selection.Copy
Cells.Replace What:=ActiveCell.Value, Replacement:="????", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End Sub
From here I am at a loss. I understand Range("A1").Select will paste into the Find section of the Find/Replace box, but how do I tell excel I want to select another Cell, in this case B1, for the replace portion? And then how do I tell Excel I want it to keep doing this until it runs out of values in the A Column?
Thank you in advance for any assistance you can provide.

I think you are after something like the code below:
Option Explicit
Sub Macro1()
Dim Rng As Range
Dim OrigStr As String, ReplaceStr As String
Set Rng = Range("A1:B3600")
OrigStr = Range("A1").Value2
ReplaceStr = Range("B1").Value2
' option 1: replace only if the whole cell's string equals to OrigStr
Rng.Replace What:=OrigStr, Replacement:=ReplaceStr, LookAt:=xlWhole
' option 2: replace also partial match inside the cell's string
Rng.Replace What:=OrigStr, Replacement:=ReplaceStr, LookAt:=xlPart
End Sub

Related

Copying cell value that starts with "=" sign and paste it as string/text

I got an exported Excel file with some values like: "=Min" or "=Min + 11op D3". (not a formula, just exported that way).
I'm doing lots of manipulations on the data and unfortunately, I cannot perform any change on the values start with the "=" sign.
so far I tried to change all cell starts with "=" to " '= " and still I cannot copy the cell content.
I'm getting the "#NAME?" error in the cell where I pasted the copied value.
I tried using that sub:
Sub changeEqualSign(colName As String)
Dim Rng As Range
Dim cell As Variant
Set Rng = getHeadersRange(colName)
Rng.Replace what:="=", Replacement:="'=", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False _
, FormulaVersion:=xlReplaceFormula2
End Sub
any ideas on how to manage coping cells with the "=" sign?
I also tried the .PasteSpecial xlPasteValues and it didn't help.
Thanks.

Search/Replace in One Column Impacting Entire Worksheet

In Column L (only) I want to replace any instance of data with "True" regardless of what was originally in any of the Column L cells. The code I tried was:
With ActiveSheet
intLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Let strSelectRange = "L2" & ":" & "L" & intLastRow
Range(strSelectRange).Select
Cells.Replace What:="*", Replacement:="True", LookAt:=xlPart _
, SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End With
First, I used .Rows.Count, "A" because in that column every row has data so I know how many rows to go down in Column L. In Column L many cells will be blank.
When I run this, every cell in the entire worksheet that has anything in it, is changed to True, not just the data in Column L.
Another method I tried was:
Range("L2:L1200").Select
Selection.Replace What:="*", Replacement:="True", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("A1").Select
What I don't like about this is that I picked L1200 as the number of rows just to be sure I'd search farther than the actual last row that can contain data. I'm worried that this method might cause some kind of problem at some point.
What I'd really like to know is what I'm doing wrong in the first code example.
Thanks for any help you can offer!!!
Search & Replace in Column
Use Option Explicit always, to quicker learn about the occurring
errors and to be forced to declare variables.
You should always declare your rows as Long.
When you use the With statement you use the dots on everything, even
on .Range and .Cells etc. The code might work in this case
(ActiveSheet) anyway, but it is incorrect.
Avoid the use of ActiveSheet, use the worksheet name.
Avoid the use of Select. There are many posts (articles) about this.
When ever you use Cells without anything behind it, it refers to all the
cells in the worksheet.
The first thing in the Replace function (Find function) is the range
where you're going to Replace (Find, Search). It can be a column, it
can be Cells or just a smaller range.
The Code
Sub SROneColumn()
Const cVntLRColumn As Variant = "A" ' Last Row Column Letter/Number
Const cVntCriteria As Variant = "L" ' Criteria Column Letter/Number
Const cLngFirstRow As Long = 2 ' First Row Number
Const cStrReplace As String = "True" ' Replace String
Dim lngLastRow As Long ' Last Row Number
Dim strSelectRange As String ' Select Range Address
With ActiveSheet
lngLastRow = .Cells(.Rows.Count, cVntLRColumn).End(xlUp).Row
strSelectRange = .Range(.Cells(cLngFirstRow, cVntCriteria), _
.Cells(lngLastRow, cVntCriteria)).Address
.Range(strSelectRange).Replace What:="*", Replacement:=cStrReplace, _
LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False
End With
End Sub
An interesting way to use a worksheet without the use of an object variable:
Sub SRSheet()
Const cStrSheet As Variant = "Sheet1" ' Worksheet Name/Index
With ThisWorkbook.Worksheets(cStrSheet)
End With
End Sub
Range(strSelectRange).Select
selects a range (though best to avoid Select) but then your code does nothing with that selection because Cells is the entire sheet.
Maybe you want instead:
Range(strSelectRange).Replace What:="*", Replacement:="True", LookAt:=xlPart

Incorporate String into a Range (Excel VBA)

I am working with a code to have a user enter in a year, to which excel would then find in a row, and then autofill the formula in that column. I have managed to be able to get the input and column aspect down, but am struggling with how to incorporate my sting into a range. Please help!
Code below.
Sub Copy_formula()
NewPageName = InputBox("Enter in Year")
Dim rFind As Range
Sheets("data_calc").Select
With Range("A2:AH2")
Set rFind = .Find(What:=NewPageName, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
MsgBox rFind.Column
End If
End With
Selection.AutoFill Destination:=Range(Cells(3, "rFind"), Cells(2393, "rFind"))
Range(Cells(3, "rFind"), Cells(2393, "rFind")).Select
End Sub
"rFind" within double quotes is a String which VBA will try to convert to a column number within a Cells() statement. As columns run from "A" to "XFD", anything beyond that should cause an error. So loose the double quotes.
However, that won't entirely solve your problem. The default return for a Range object is its .Value property.
What you want is the Range.Column property.
So change your Range(Cells(3, "rFind"), Cells(2393, "rFind")) to:
Range(Cells(3, rFind.Column), Cells(2393, rFind.Column))

How to find the address of a cell found by LOOKUP?

I use the following formula to get the last non-zero value in a column:
ActiveSheet.Range("A5").Formula = "= LOOKUP(2,1/(H:H>1),H:H)"
It works nicely. But I would like to get the address of that cell. I have tried several lines of code found here and there and most boil down to something like this:
`Dim rb as Range
rb ="LOOKUP(2,1/(H:H>1),H:H)"
MsgBox(rb.Address)
MsgBox(rb.Row)
MsgBox(rb.Column)`
It goes without saying that it does not work. How can one find the address of the cell that LOOKUP returns? Thank you very much in advance.
If you want to stick with VBA, and use your original concept, you can use your current Formula, and afterwards use Find function to look from the end to find the row.
Code
Option Explicit
Sub GetAddressofLookup()
Dim FindRng As Range
ActiveSheet.Range("A5").Formula = "= LOOKUP(2,1/(H:H>1),H:H)"
Set FindRng = ActiveSheet.Columns("H").Find(what:=ActiveSheet.Range("A5").Value, Lookat:=xlPart, LookIn:=xlFormulas, _
searchorder:=xlByRows, searchdirection:=xlPrevious, MatchCase:=False)
MsgBox FindRng.Address
End Sub
This worksheet formula will give the address of the last value in column H that is greater than zero:
="H"&LOOKUP(2,1/(H:H>0),ROW(H:H))
In VBA:
Sub dural()
MsgBox "H" & Evaluate("LOOKUP(2,1/(H:H>0),ROW(H:H))")
End Sub

Insert row after specific text is found

I am fairly new to excel and I am trying to setup a macro that adds a row after a specific point of the worksheet. Example: Row 2 contains text "Original", so it should insert a new row afterwards, and so on.
I know that it might be easier to insert before something, so I could change the setup (so for example the word "original" would be in row 2 and the new row is added above it) if that is an easier solution.
Is this possible? How?
Thanks for all the possible help.
Slightly simpler than the previous answer:
Sub NewRowInsert()
Dim SearchText As String
Dim GCell As Range
SearchText = "Original"
Set GCell = Cells.Find(SearchText).Offset(1)
GCell.EntireRow.Insert
End Sub
This will work with the current active sheet. If you want to use some other sheet, say Sheet2, you could use:
Set GCell = Worksheets("Sheet2").Cells.Find(SearchText).Offset(1)
and if you wanted to operate on a different workbook e.g. TestBook.xlsx, you could use:
Set GCell = Workbooks("TestBook.xlsx").Worksheets("Sheet2").Cells.Find(SearchText).Offset(1)
Note that I've avoided the use of select. This may not be an issue for you, but if you're searching through thousands of rows and making many replacements it could speed up your code considerably.
Try the code below = you can change the textvalue variable value to what ever you want to search for.
Sub newRow()
Dim textvalue As String
textvalue = "Original"
Cells.Find(What:=textvalue, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.offset(rowOffset:=1, columnOffset:=0).Activate
ActiveCell.EntireRow.Insert
End Sub

Resources