PDA

View Full Version : Find and replace (Excel&Word)



mprija
06-08-2008, 04:40 AM
I have a macro which finds and replaces words and phrases in Excel sheet1 based on data saved in sheet2 (sheet2 acts like a database). For example if word from A1 on sheet2 exist on sheet1 then it will be changed with word from B1 (sheet2). Here is the code:
Sub String_Translator()
Dim lLoop As Long
Dim strReplace
Dim strReplaceWith

'two columns
strReplace = Sheet2.Range("A1:A600")
strReplaceWith = Sheet2.Range("B1:B600")

For lLoop = 1 To 600
Sheet1.Cells.Replace strReplace(lLoop, 1), strReplaceWith(lLoop, 1)
Next lLoop
End Sub

Now I would like to do something similar on a MS Word document (example.doc), but I do not have a clue where to start. I would like to use Sheet2 in my Excel document (data.xls) as database. So if same word is in MS Word document and in column A then this word must be replaced in MS Word document (example.doc) with word from Sheet2/column B (data.xls).
In attached data.xls,there is a Sheet named example.doc, which should be in separate example.doc file, but because of one file upload limit on this forum, i have copy/pasted it as a MS Office Word Document Object.
Guys if someone can help me with it I will be gratefull.

Jan Karel Pieterse
06-09-2008, 01:20 AM
No answer to your Word question,but some advice
I'd change your code so it only does the cells actually containing something:




Sub String_Translator()
Dim lLoop As Long
Dim strReplace
Dim strReplaceWith

'two columns
strReplace = Sheet2.Range("A1:A600")
strReplaceWith = Sheet2.Range("B1:B600")

For lLoop = 1 To Sheet2.Range("A" & Sheet2.Rows.Count).End(xlUp).Row
Sheet1.Cells.Replace strReplace(lLoop, 1), strReplaceWith(lLoop, 1)
Next lLoop
End Sub