Find and replace- from a table - replace

I am a beginner in Macro, in my office I have a work like on one workbook we have two columns one column with english words and another column with russian words this file is master. I have to find and replace this english with russian in another work book with range M51(range varies), I need the macro for this.

for the FIND and REPLACE values entered on Sheet 1, and carries out the F&R on Sheet2.
Caveats as before
Dim Findtext As String
Dim Replacetext As String
Findtext = Sheets("Sheet1").Range("B2").Value
Replacetext = Sheets("Sheet1").Range("C2").Value
Sheets("Sheet2").Select
Cells.Replace What:=Findtext, Replacement:=Replacetext, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

Related

Visual Basic Multiple Regex inserting into DataGridView

Below is part of my code for a small webscraping project I'm working on. I'm having an issue inserting the values of the second Regex into the datagrid and have them line up with the values of the first regex. Each page will have a list of ten items, each with a unique ID along with a format and a rating. When the code is run, it only adds the formatID data to the first ten rows.
Dim r As New System.Text.RegularExpressions.Regex("<div id=""R.*"" class=""a-section review"">")
Dim Matches As MatchCollection = r.Matches(SourceCode)
For Each ItemID As Match In Matches
DataGridView1.Rows.Add("", Split(ItemID.Value, """").GetValue(1), AsinTextBox.Text, "", "", "", "")
Next
Dim R2 As New System.Text.RegularExpressions.Regex("<a class=""a-size-mini a-link-normal a-color-secondary"" href=""/.*/product-reviews/.*/ref=.*"">.*</a>")
Dim Matches2 As MatchCollection = R2.Matches(SourceCode)
Dim Z2
Dim i As Integer = 0
For Each FormatID As Match In Matches2
i = i + 1
Z2 = Split(FormatID.Value, ">").GetValue(1)
Z2 = Split(Z2, "<").GetValue(0)
DataGridView1.Rows(i).Cells(5).Value = (Z2)
Next
I figured it out. Instead of doing multiple Regex searches, I did one larger one that incorporated all of the three that I was trying to do previously. The three regex searches from before were all apart of one large string of html and after I had searched for it I used the split function to get the correct value for Z2.

Why does Find/Replace zRngResult.Find work fine, but RegEx myRegExp.Execute(zRngResult) mess up the range.Start?

I wish to select and add comments after certain words, e.g. “not”, “never”, “don’t” in sentences in a Word document with VBA. The Find/Replace with wildcards works fine, but “Use wildcards” cannot be selected with “Match case”. The RegEx can “IgnoreCase=True”, but the selection of the word is not reliable when there are more than one comments in a sentence. The Range.start seems to be getting modified in a way that I cannot understand.
A similar question was asked in June 2010. https://social.msdn.microsoft.com/Forums/office/en-US/f73ca32d-0af9-47cf-81fe-ce93b13ebc4d/regex-selecting-a-match-within-the-document?forum=worddev
Is there a new/different way of solving this problem?
Any suggestion will be appreciated.
The code using RegEx follows:
Function zRegExCommentor(zPhrase As String, tComment As String) As Long
Dim sTheseSentences As Sentences
Dim rThisSentenceToSearch As Word.Range, rThisSentenceResult As Word.Range
Dim myRegExp As RegExp
Dim myMatches As MatchCollection
Options.CommentsColor = wdByAuthor
Set myRegExp = New RegExp
With myRegExp
.IgnoreCase = True
.Global = False
.Pattern = zPhrase
End With
Set sTheseSentences = ActiveDocument.Sentences
For Each rThisSentenceToSearch In sTheseSentences
Set rThisSentenceResult = rThisSentenceToSearch.Duplicate
rThisSentenceResult.Select
Do
DoEvents
Set myMatches = myRegExp.Execute(rThisSentenceResult)
If myMatches.Count > 0 Then
rThisSentenceResult.Start = rThisSentenceResult.Start + myMatches(0).FirstIndex
rThisSentenceResult.End = rThisSentenceResult.Start + myMatches(0).Length
rThisSentenceResult.Select
Selection.Comments.Add Range:=Selection.Range
Selection.TypeText Text:=tComment & "{" & zPhrase & "}"
rThisSentenceResult.Start = rThisSentenceResult.Start + 1 'so as not to find the same phrase again and again
rThisSentenceResult.End = rThisSentenceToSearch.End
rThisSentenceResult.Select
End If 'If myMatches.Count > 0 Then
Loop While myMatches.Count > 0
Next 'For Each rThisSentenceToSearch In sTheseSentences
End Function
Relying on Range.Start or Range.End for position in a Word document is not reliable due to how Word stores non-printing information in the text flow. For some kinds of things you can work around it using Range.TextRetrievalMode, but the non-printing characters inserted by Comments aren't affected by these settings.
I must admit I don't understand why Word's built-in Find with wildcards won't work for you - no case matching shouldn't be a problem. For instance, based on the example: "Never has there been, never, NEVER, a total drought.":
FindText:="[n,N][e,E][v,V][e,E][r,R]"
Will find all instances of n-e-v-e-r regardless of the capitalization. The brackets let you define a range of values, in this case the combination of lower and upper case for each letter in the search term.
The workarounds described in my MSDN post you link to are pretty much all you can if you insist on RegEx:
Using the Office Open XML (or possibly Word 2003 XML) file format will let you use RegEx and standard XML processing tools to find the information, add comment "tags" into the Word XML, close it all up... And when the user sees the document it will all be there.
If you need to be doing this in the Word UI a slightly different approach should work (assuming you're targeting Word 2003 or later): Work through the document on a range-by-range basis (by paragraph, perhaps). Read the XML representation of the text into memory using the Range.WordOpenXML property, perform the RegEx search, add comments as WordOpenXML, then write the WordOpenXML back into the document using the InserXml method, replacing the original range (paragraph). Since you'd be working with the Paragraph object Range.Start won't be a factor.

Find word with RegExp and bold

I've a word document where I want to find all the words as have the following layout: ABC-12:123456 DEF. Where this is found in the document the word should be selected and put in bold. (Later i'll add a hyperlink instead of bold). I have successfully found the word and put it in a MatchCollection just to try RegExp. It looks like:
Sub searchDocument()
Set matchPattern = New RegExp
matchPattern.Pattern = "ABC-\d{2}:\d{6} DEF"
matchPattern.Global = True
Dim matchPatternWords As MatchCollection
Set matchPatternWords = matchPattern.Execute(ActiveDocument.Range)
For Each matchPatternWord In matchPatternWords
MsgBox (matchPatternWord)
Next matchPatternWord
End Sub
You need to go from the regexp match to the range object representing the match.
matchRange = ActiveDocument.Range
(matchPatternWord.FirstIndex, matchPatternWord.FirstIndex+matchPatternWord.Length)
would be the obvious invocation.
However this post indicates that there might be issues with this approach, because formating can mess up the character count. It's from 2010 though so the issue might be resolved in a better way now.
If the above doesn't work, or if you don't trust it you can do;
matchRange = ActiveDocument.Range.Find(FindText:=matchPatternWord.Value)
The latter needs a bit more handeling if multiple occurences of the same word is a possibility.
Once you have the range it's straight forward.
matchRange.Bold = True

Replace string in file using VB.net - case insensitive

Given the following partial file example :
<SellGrey>True</SellGrey>
<SellWhite>false</SellWhite>
<SellGreen>false</SellGreen>
<SellBlue>false</SellBlue>
What is the best method to do a case-insensitive search and replace, while keeping the proper case on output.
For example:
<SellGrey>True</SellGrey>
or
<Sellgrey>tRue</Sellgrey>
would be what I am searching for, but the replacement, would always be :
<SellGrey>False</SellGrey>
Lastly, please do not get hung up on the "tags" as the file is malformed xml so reading/writing xml would bugger things up. Please look at the strings as just that -- a case-insensitive string search and replace, on a line by line basis.
Thanks in advance.
Since you didn't provide much detail about the tags, I used a dictionary for proper casing.
Dim input as String = "<Sellgrey>tRue</Sellgrey>"
Dim pattern as String = "<(?<tag>.+)>(?<value>(true|false))</.+>"
'building a dictionary to specify how to proper case
Dim tagFormatter as new Dictionary(Of String, String)
tagFormatter.Add("sellgrey", "ShellGrey")
tagFormatter.Add("sellwhite", "SellWhite")
tagFormatter.Add("sellgreen", "SellGreen")
tagFormatter.Add("sellblue", "SellBlue")
'build the new string using lambda
Dim result = Regex.Replace(input, pattern, _
Function(m) String.Format("<{0}>{1}</{0}>", _
tagFormatter(m.Groups("tag").Value.ToLower), _
If(m.Groups("value").Value = "true", "True", "False")), _
RegexOptions.IgnoreCase)

Split one table's column into two columns based on value

I have a table with so many rows. It's structure is like this picture:
As you can see i have "or", "And" between names in columns A. How i can splite these column into twi parts?. IN that case i will have David, Tylor, Fred, Jessi, Roland in the firstcolumn and Peter, Mark, Alfered, Hovard and DAvid in the second.
Note: Please pay attention to row 2 and 5. in these rows i have 2 "or" or two "and".
Edit: I prefer to do that in Excel
What I Have Tried
As one possible solution, i have this function in vba.
Function udfRegEx(CellLocation As Range, RegPattern As String)
Dim RegEx As Object, RegMatchCollection As Object, RegMatch As Object
Dim OutPutStr As String
Dim i As Integer
i = ActiveWorkbook.Worksheets(ActiveWorksheet.Name).UsedRange.rows.Count
Set RegEx = CreateObject("vbscript.regexp")
With RegEx
.Global = True
.Pattern = RegPattern
End With
OutPutStr = ""
Set RegMatchCollection = RegEx.Execute(CellLocation.Value)
For Each RegMatch In RegMatchCollection
OutPutStr = OutPutStr & RegMatch
Next
udfRegEx = OutPutStr
Set RegMatchCollection = Nothing
Set RegEx = Nothing
Set Myrange = Nothing
End Function
This function uses Regex. but i don't know how to use that.
As I mentioned that you do not need VBA for this. An Excel formula will also do what you need.
My Assumptions
Col A has the data
You want the output in Col B and Col C
Paste this formula in Cell B1 and copy it down
=IF(ISERROR(SEARCH(" or ",A1,1))=TRUE,IF(ISERROR(SEARCH(" and ",A1,1))=TRUE,"",LEFT(A1,SEARCH(" and ",A1,1))),LEFT(A1,SEARCH(" or ",A1,1)))
and this in Cell C1 and copy it down
=IF(ISERROR(SEARCH(" or ",A1,1))=TRUE,IF(ISERROR(SEARCH(" and ",A1,1))=TRUE,"",MID(A1,SEARCH(" and ",A1,1)+5,LEN(A1)-SEARCH(" and ",A1,1))),MID(A1,SEARCH(" or ",A1,1)+4,LEN(A1)-SEARCH(" or ",A1,1)))
SNAPSHOT
(\w)+(( or | and ){0,1}(\w)+)*
Its not a coding solution, but since you did not ask for code (and because its not necessary in this case), simply do a find/replace on the words "and" and "or" to replace them with some delimiter (e.g. replace them with a comma). Then in excel, you can select the data, and split them into different columns using excels "text to columns" feature (on the data tab in excel 2007).