I would like to do a replace all using VBnet 2003 and MSword 2007.
I got to this
Dim Selection As Word.Selection
Selection.Find.ClearFormatting()
Selection.Find.Replacement.ClearFormatting()
Selection.Find.Replacement.Font.Underline = Word.WdUnderline.wdUnderlineSingle
With Selection.Find
.Text = "Text"
.Replacement.Text = "Replacement"
.Forward = True
.Format = True
.Wrap = Word.WdFindWrap.wdFindContinue
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
Selection.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)
It crashes EVERY line with the selection claiming that "Object reference not set to an instance of an object." I got the code by doing a macro recording and it worked fine as a macro but I do not want macros in my document. How do I fix this?
First you need to link to Word and the document. This code assumes Word is running with the correct document loaded and displayed.
Dim WordApplication As Word.Application = GetObject(, "Word.Application")
Dim Document As Word.Document = WordApplication.ActiveDocument
Document.Select()
Dim Selection As Word.Selection = Document.ActiveWindow.Selection
' Do your thing here.
Related
I wrote code in Word to find "[edit]" links in a document, break the hyperlink, and delete the text.
I would like to adapt this to run in Outlook. I have gone to tools>references to allow Outlook to access Word object library, and inserted the following code before my "DeleteEditLinks" macro:
Dim Ins As Outlook.Inspector
Dim Document As Word.Document
Dim Word As Word.Application
Dim Selection As Word.Selection
Set Ins = Application.ActiveInspector
Set Document = Ins.WordEditor
Set Word = Document.Application
Set Selection = Word.Selection
The final code looks like this:
Public Sub DeleteEditLinks()
Dim Ins As Outlook.Inspector
Dim Document As Word.Document
Dim Word As Word.Application
Dim Selection As Word.Selection
Set Ins = Application.ActiveInspector
Set Document = Ins.WordEditor
Set Word = Document.Application
Set Selection = Word.Selection
Dim oField As Field ' breaks hyperlinks of "[edit]" links, and deletes them
For Each oField In ActiveDocument.Fields
If oField.Type = wdFieldHyperlink Then
If Left(oField.Result, 4) = "edit" Then
oField.Unlink
End If
End If
Next
Set oField = Nothing
Dim sample
sample = "[edit]"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = sample
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
How do I adapt this to run on the text of an Outlook email?
I'm not sure how Fields object must appear in the outlook, as well as what ecxatly you are trying to achieve, but!.. I've found basic issues in your code, so, my solution might be helpful.
You refer to ActiveDocument within as it is a part of Outlook objects collection. It is not, so you need to refer to the Document object which you've correctly created from inspector. The same with Selection.
I used late binding (Dim oField As Object), not sure if with early binding and "tools>references" option on you also have this trouble, but word constants wdFindContinue were not recognized so I used values for them (just googled them).
So, if in your target e-mails there are fields somehow - your updated code below should work... Please write if not the case.
Public Sub DeleteEditLinks()
Dim Ins As Outlook.Inspector
Dim Document As Object
Dim oField As Object
Dim sample As String
Set Ins = Application.ActiveInspector
Set Document = CreateObject("Word.Document")
Set Document = Ins.WordEditor
For Each oField In Document.Fields
If oField.Type = 88 Then
If Left(oField.Result, 4) = "edit" Then
oField.Unlink
End If
End If
Next
Set oField = Nothing
sample = "[edit]"
Document.Application.Selection.Find.ClearFormatting
Document.Application.Selection.Find.Replacement.ClearFormatting
With Document.Application.Selection.Find
.Text = sample
.Replacement.Text = ""
.Forward = True
.Wrap = 1
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=2
End With
End Sub
I get run-time error 13 (Type Mismatch) on my code when I try to run it.
I'm trying to replace a text in a opened Word document through Excel, inside the header.
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open(myPath & "\Armaturförteckning.docx")
' Ändrar i Armaturförteckningen
Dim rngStory As Range
Dim lngJunk As Long
'Fix the skipped blank Header/Footer problem as provided by Peter Hewett
lngJunk = WordApp.ActiveDocument.Sections(1).Headers(1).Range.StoryType
'Iterate through all story types in the current document
For Each rngStory In WordApp.ActiveDocument.StoryRanges
'Iterate through all linked stories
Do
With WordApp.rngStory.Find
.Text = "ELESTATUS01"
.Replacement.Text = "I'm found"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
'Get next linked story (if any)
Set rngStory = WordApp.rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
' Stänger dokumentet
WordApp.Documents.Save
WordApp.ActiveDocument.Close
I believe you are trying to do a VBA search and replace. We have a BUNCH of functions that we use, and after many years of refinement, the following is what we use. It's purely the function that performs a search and replace.
Function SimpleSearchAndReplace(SomeDocument As Word.Document, SearchString As String, ReplaceString As String)
With SomeDocument.Content.Find
.Text = SearchString
.Replacement.Text = ReplaceString
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Function
It seems awkward that you have "WordApp.ActiveDocument." when what you probably need is "WordDoc." in your 'lngJunk' and 'For Each' lines.
I am using this VBA code for covnvert textbox text to regular text. But its through errors on shp.Type and sString = Left(shp.TextFrame.TextRange.Text, _
shp.TextFrame.TextRange.Characters.Count - 1), while i am compiling in VB.
What should i change in the code for VB?
This is VBA code:
Sub ConvertTextBoxToText()
Dim shp As Shape
Dim oRngAnchor As Range
Dim sString As String
For Each shp In ActiveDocument.Shapes
If shp.Type = msoTextBox Then
' copy text to string, without last paragraph mark
sString = Left(shp.TextFrame.TextRange.Text, _
shp.TextFrame.TextRange.Characters.Count - 1)
If Len(sString) > 0 Then
' set the range to insert the text
Set oRngAnchor = shp.Anchor.Paragraphs(1).Range
' insert the textbox text before the range object
oRngAnchor.InsertBefore sString
End If
shp.Delete
End If
Next shp
'Strip out beginning and ending textbox markers
Selection.HomeKey unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "Textbox start << "
.Replacement.Text = ""
.Forward = True
' .Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
With Selection.Find
.Text = ">> Textbox end"
.Replacement.Text = ""
.Forward = True
.wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
VB Code:?
Could you please?
VB uses VBA as it's language. So no conversion needed. VB is an app object and forms package that hosts VBA, like Word is a Word Processor that hosts VBA.
In your code you don't connect to Word. In Word, some objects are made automatically available. Outside of Word you have to connect to them.
Set xlBook = GetObject("C:\Users\User\Documents\Super.xls")
For each wsheet in xlbook.worksheets
msgbox wsheet.name
wsheet.printOut
next
or
set xlapp = createobject("Excel.Application")
xlapp.Workbooks.Open "C:\Users\User\Documents\Super.xls"
'43 is 95/97 look up xlExcel9795 in object browser to see other options
xlapp.ActiveWorkbook.SaveAs "C:\Users\User\Documents\Super.xls", 43
or
Set GetExcelApp = GetObject("", "Excel.Application")
Msgbox GetExcelApp
The error occurs as described in below steps:
1. If i search a keyword then the searched keyword is higlighted.
2.The next time i search something the previous search results that were highlighted remains.
3.How to remove the previous highlights that i made
Private Sub Search_Button_Click(sender As Object, e As EventArgs) Handles Search_Button.Click
Dim wordApp As Word.Application, currentDoc As Word.Document
wordApp = DirectCast(GetObject(, "Word.Application"), Word.Application)
currentDoc = wordApp.ActiveDocument
With currentDoc.Content.Find
.MatchCase = False
.ClearFormatting()
.Text = SearchBox.Text
With .Replacement
.ClearFormatting()
.Text = SearchBox.Text
.Highlight = Word.WdColor.wdColorTurquoise
End With
.Execute(Replace:=Word.WdReplace.wdReplaceAll)
End With
End Sub
End Class
I am learning to automate word using VB.NET. Are there any tutorials for beginners so please suggest.
Try something like this (in reference to your code):
With currentDoc.Content.Find
.ClearFormatting()
.Highlight = True
With .Replacement
.ClearFormatting()
.Highlight = False
'see additional comment below to this point of the code
End With
.Execute(Replace:=Word.WdReplace.wdReplaceAll)
End With
Comment: sometimes it's required to add additional parameter(s) when working with find >> replace. If above presented syntax is not working try to add some (or all) of properties in the point I commented in the code above:
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
I need to go through a row in excel table and use cell values to do replacements in Word document. I used record macro to get the code, it actually replaces the text. But when I use it from Excel Macros it doesn't work.
Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Dim WordDoc As Object
Set WordDoc = WordApp.Documents.Open(doc_path_str)
Dim find_what, find_repl As String
For col_idx = params_hdr_range.Column To params_hdr_range.Column + params_hdr_range.Columns.Count - 1
find_what = CStr(scnd_sheet.Cells(params_hdr_range.Row - 1, col_idx).Value)
find_repl = CStr(scnd_sheet.Cells(model_found_range.Row, col_idx).Value)
WordApp.Selection.Find.ClearHitHighlight
WordApp.Selection.Find.ClearFormatting
WordApp.Selection.Find.Replacement.ClearFormatting
With WordApp.Selection.Find
.Text = find_what
.Replacement.Text = find_repl
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
WordApp.Selection.Find.Execute Replace:=wdReplaceAll
Next col_idx
find_what and find_repl have proper values ("{MODEL}" and "F22-2"), the same ones I used when recorded the macro, but no replacements are made. The only thing this code does it selects the text "{MODEL}" in the document. But it doesn't replace it, and though it goes through a lot of columns and other values (e.g. "{PRICE}"), nothing else happens.
How can I fix this?
Unless you add a reference to the Word object library in your Excel VBA project, Excel isn't going to know the values of Word constants such as wdReplaceAll.
You can either add the reference, declare the constants in your Excel VBA, or use the constants' values instead (which can be found in the Word VBA Object Browser)