Find and replace using VBA - excel

I have a chart where I need to remove certain keywords from column C- Range C3:C5000(some cells are blank). The words that needs to be removed are placed in column A- Range A3:A100(some cells are blank). Both ranges gets changed for different files. I have written a code but its not working for dynamic range. Also I want to sort column c according to no. of characters in cell in Ascending order. please help
Sub Replace_Char()
Dim i As Integer
Dim Mpp As String
For i = 3 To 50
Mpp = Cells(i, 1).Value
If Cells(i, 1).Value <> 0 Then
Worksheets("Sheet1").Columns("C").Replace _
What:=Mpp, Replacement:="", _
SearchOrder:=xlByColumns, MatchCase:=True
End If
Next i
End Sub

For dynamic ranges, you can try using the .UsedRange property.
As for sorting by number of characters, create a column that has the formula like "=LEN(D1)" and then sort the sheet on that column.
Sub Replace_Char()
Dim i As Integer
Dim Mpp As String
'For i = 3 To 50
Dim Thing As Range
For Each Thing In ActiveSheet.UsedRange.Columns(1).Cells
Mpp = Cells(i, 1).Value
If Cells(i, 1).Value <> 0 Then
Worksheets("Sheet1").Columns("C").Replace _
What:=Mpp, Replacement:="", _
SearchOrder:=xlByColumns, MatchCase:=True
End If
'Next i
Next
End Sub

Related

Merge 2 columns and find text VBA

I have one table and one file. I can find the text which is in specific place in file inside the table.
However, the texts are not unique all the time, so I decided to combine 2 cells in file and try to find in table. unless, I cannot find a way to combine 2 columns in table to match it with combined 2 cells in file.
Below you may see example table.
my aim is adding date in cell next cell of Units. So I try to find A1234 instead of 1234 due to 1234 not unique.
FindString = wb.Sheets("1").Range("E4").Value & wb.Sheets("1").Range("E5").Value
If Trim(FindString) <> "" Then
With Wb2.Sheets("Sheet1").Range("A:A") 'this section need to be amended and need combine column A&B
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not Rng Is Nothing Then
Rng.Offset(0, 1).Value = wb.Sheets("1").Range("I4") ' if column A&B combining completed then next cell probably will not work
Else
MsgBox "Nothing found in the list"
End If
This is similar to the variant strategy mentioned in the comments-- Try looping through your data with a For loop and an If Statement looking for both values to match. Here's an example code that shows the concept
Sub test()
Dim s As Worksheet, findstring1 As String, findstring2 As String
Dim firstrow As Integer, lastrow As Integer, i As Integer
Set s = Sheets("test")
findstring1 = "A "'replace this with the Customer reference (what to search for)
findstring2 = "1234" 'replace this with the unit reference
firstrow = 2 ' row number for first cell with data
lastcell = s.Cells(2, 1).End(xlDown).Row 'find last cell row number (end of data)
For i = firstrow To lastcell
If s.Cells(i, 1) = findstring1 And s.Cells(i, 2) = findstring2 Then
'do something with found values
End If
Next i
End Sub

How do I loop through a row of data, pull value from specific cell in that row, find it in another row, then enter a value in the intersecting box

So i have a workbook. Rows 1-3 are header info. Row 4 starting in column C is dates from Jan 1 2020 to Dec 31, 2020. Then I have names of Employee's in Column A from A5:A:16. Then from B:5:B16 i have their start dates (formatted exactly the same as the dates in row 4). I am trying to loop through A:5-A:20 and if there is a name there, get the value from row B (Their start date) and find that value in row 4 (Which is where the dates are) to get the column, and then put a "n" in the cell that will intersect their name and start date. But when i press my button or run my code, nothing happens.
Sub Button1_Click()
Dim i As Long
Dim lnCol As Long
For i = 5 To Range("A20")
If Not IsEmpty(Cells(i, 1).Value) Then
StartDate = Cells(i, 2).Value
lnCol = Sheet3.Cells(4, 1).EntireRow.Find(What:=StartDate, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).column
Cells(i, lnCol).Value = "n"
End If
Next i
End Sub
You could try:
Sub Test()
Dim cl As Range
Dim col As Long
With Sheet1 'Change to sheets CodeName you interested in
For Each cl In .Range("A5:A20").SpecialCells(2, 2)
col = .Range("4:4").Find(What:=cl.Offset(, 1).Value, LookIn:=xlValues, Lookat:=xlWhole).Column
.Cells(cl.Row, col).Value = "n"
Next cl
End With
End Sub
Note: .Range("A5:A20").SpecialCells(2, 2) will only work when you positive there is at least one name. This prevents a full iteration. However, when all are empty will raise an error
Edit
According to your comment:
"Yes right now only A5:A16 are filled. I wanted to make the formula search a larger range for when we add people."
I think what you actually wanted is a dynamic way to retrieve the last used row. In that case try the below:
Sub Test()
Dim cl As Range
Dim col As Long
With Sheet1 'Change to sheets CodeName you interested in
For Each cl In .Range("A5:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
col = .Range("4:4").Find(What:=cl.Offset(, 1).Value, LookIn:=xlValues, Lookat:=xlWhole).Column
.Cells(cl.Row, col).Value = "n"
Next cl
End With
End Sub

VBA Excel - Search rows for string and if found copy entire cell to a specific location

I got 3000 rows of data in Excel.
Each row contains the same type of information but not in the right order.
What i need to do is to gather the same type of information under the same column.I would like to create a macro that is going to:
Search a row for a partial string (some values have similar strings but fall under different categories)
If the string is part of a cell copy the entire cell in a
new location
Repeat for the next row
Thanks in advance
Sub MoveColumns()
Dim LastRow As Long
Dim rFind As Range
Dim r As String
Dim m As Integer
LastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row
MsgBox (LastRow)
For n = 1 To LastRow
r = n & ":" & n
Range(r).Select
With Range(r)
Set rFind = .Find(What:="Spain*", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
If rFind.Column < 6 Then
m = 6 - rFind.Column
Range(Cells(n, 1), Cells(n, m)).Insert Shift:=xlToRight
ElseIf rFind.Column > 6 Then
m = rFind.Column - 6
Range(Cells(n, 1), Cells(n, m)).Delete Shift:=xlToLeft
End If
End If
End With
Next
End Sub
UPDATED
If row doesn't contain any value starts with "Spain", this row is simply ignored and skipped.
I hope you can modify and customize the way suitable for your data.

Excel: move the contents of the row to a specific column based on condition

I have a large excel file with consistent columns but they're not placed too accurately;
The example in the photo is illustrative to my problem; I'm only interested in the information after the "country" column.
Therefore, within each row, I would like to
1. check each row to find a specific string of characters - in this case "Spain".
2. move the row so that the cells with the strings found are all on the same column.
In the example below, all the rows should be moved so that "Spain" is under column F - arranging the rest of the info with it.
If word Spain isn't changed, use this VBA code:
Sub MoveCoun()
Dim LastRow As Long
Dim rFind As Range
Dim r As String
Dim m As Integer
LastRow = 1000
For n = 1 To LastRow
r = n & ":" & n
Range(r).Select
With Range(r)
Set rFind = .Find(What:="Spain", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
If rFind.Column < 6 Then
m = 6 - rFind.Column
Range(Cells(n, 1), Cells(n, m)).Insert Shift:=xlToRight
ElseIf rFind.Column > 6 Then
m = rFind.Column - 6
Range(Cells(n, 1), Cells(n, m)).Delete Shift:=xlToLeft
End If
End If
End With
Next
End Sub

Use Find/Replace to clear vbNullString

I have a spreadsheet that is generated as a report in our Enterprise system and downloaded into an Excel spreadsheet. Blank cells in the resulting spreadsheet are not really blank, even though no data is present - and the blank cells do Not contain a 'space' character.
For example, the following cell formula in A2 returns TRUE (if A1 is a blank cell):
=IF(A1="","TRUE","FALSE")
However,
=ISBLANK(A1)
returns FALSE.
You can replicate this problem by typing an apostrophe (') in a cell and copying the cell. Then, use Paste Special...Values to paste to another cell and the apostrophe is not visible in the pasted cell, nor in the Formula Bar. There appears to be a clear cell, but it will evaluate to FALSE using ISBLANK.
This causes sorting to result in the fake blank cells at the top of an ascending sort, when they need to be at the bottom of the sort.
I can use a vba loop to fix the fake blanks, to loop through every column and evaluate
IF Cell.VALUE = "" Then
Cell.Clear
but because the spreadsheet has tens of thousands of rows of data and as many as 50 columns, this adds substantial overhead to the program and I would prefer to use FIND and Replace.
Here is the code that does not currently work:
Range("ZZ1").Copy
Range("Table1[#All]").Select
With Selection
.Replace What:="", Replacement:=.PasteSpecial(xlPasteValues, xlNone, False, False), _
LookAt:=xlWhole, SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End With
The following things do not work to clear the fake blank cells either:
Replacement:= vbnullstring
Replacement:= ""
Replacement:= Cells.Clear
Replacement:= Cells.ClearContents
Replacement:= Cells.Value = ""
I have tried 20 other things that do not work either.
Try this
With ActiveSheet.UsedRange
.NumberFormat = "General"
.Value = .Value
End With
A variant array provides an efficient way of handling the false empties:
Sub CullEm()
Dim lngRow As Long
Dim lngCol As Long
Dim X
X = ActiveSheet.UsedRange.Value2
For lngRow = 1 To UBound(X, 1)
For lngCol = 1 To UBound(X, 2)
If Len(X(lngRow, lngCol)) = 0 Then X(lngRow, lngCol) = vbNullString
Next
Next
ActiveSheet.UsedRange.Value2 = X
End Sub
The problem is that you are searching for a hidden .PrefixCharacter which are not covered by the standard replacement function. For more information on this you might want to visit MSDN: https://msdn.microsoft.com/en-us/library/office/ff194949.aspx
In order to find and replace these you'll have to use the .Find function because it can look at the formulas (rather than only at a cell's value). Here is a short sample code to illustrate that:
Option Explicit
Public Sub tmpTest()
Dim cell As Range
Dim rngTest As Range
Dim strFirstAddress As String
Set rngTest = ThisWorkbook.Worksheets(1).Range("A1:G7")
Set cell = rngTest.Find("", LookIn:=xlFormulas, lookat:=xlPart)
If Not cell Is Nothing Then
strFirstAddress = cell.Address
Do
cell.Value = vbNullString
Set cell = rngTest.FindNext(cell)
Loop While strFirstAddress <> cell.Address And Not cell Is Nothing
End If
End Sub
I can't figure out anything that you could put in Replacement to get that to work. I'm afraid you're stuck looping. You can reduce the overhead by using .Find instead of looping through every cell.
Sub ClearBlanks()
Dim rng As Range
Dim rFound As Range
Dim sFirstAdd As String
Dim rFoundAll As Range
Set rng = Sheet1.UsedRange
Set rFound = rng.Find(vbNullString, , xlValues, xlWhole)
If Not rFound Is Nothing Then
sFirstAdd = rFound.Address
Do
If rFoundAll Is Nothing Then
Set rFoundAll = rFound
Else
Set rFoundAll = Application.Union(rFound, rFoundAll)
End If
Set rFound = rng.FindNext(rFound)
Loop Until rFound.Address = sFirstAdd
End If
If Not rFoundAll Is Nothing Then
rFoundAll.ClearContents
End If
End Sub
You can use the table filter to select the (seemingly) blank cells in each column and clear the contents. This should be quicker than finding each blank cell.
Sub clearBlankTableEntries()
Dim tbl As ListObject, c As Byte
Set tbl = ActiveSheet.ListObjects("testTable")
For c = 1 To tbl.Range.Columns.Count
tbl.Range.AutoFilter Field:=c, Criteria1:="="
Range(tbl.Name & "[Column" & c & "]").ClearContents
tbl.Range.AutoFilter Field:=c
Next c
End Sub

Resources