I'm trying to write in a word document via VB.net and for this I'm using contentControls in my Word Document but sometimes I have to delete a contentControl or another via VB code.
It's kind of easy with contentcontrol.delete but when this contentControl contains multipleline and I want to delete it then it leaves a blank line. How can I avoid this?
I will give you some tips based on VBA which I hope you could easily convert to vb.net and your solution.
You need to cover complete range of ContentControl including beginning and end of the object. You could do it in this way (VBA code for first CC in activedocument):
With ActiveDocument.ContentControls(1)
'just to make a presentation- let's select range to be deleted
ActiveDocument.Range(.Range.Start - 1, .Range.End + 2).Select
'and we delete selection
Selection.Delete
End With
Obviously you could combine .Select and .Delete lines into one to avoid selection in this way:
With.... and so on
ActiveDocument.Range(.Range.Start - 1, .Range.End + 2).Delete
End with
Related
I use a long Excel spreadsheet containing incorrect and correct terms to check consistency between documents (e.g. anti-citrullinated is always hyphenated). I've added quite a few of these as autocorrect entries via the AutoCorrect Options feature in Word but it's time-consuming .
I came across the following code that will add long lists of autocorrects.
Sub BatchAddAutoCorrectEntries()
Dim objTable As Table
Dim objOriginalWord As Cell
Dim objOriginalWordRange As Range
Dim objReplaceWordRange As Range
Dim nRowNumber As Integer
Set objTable = ActiveDocument.Tables(1)
nRowNumber = 1
For Each objOriginalWord In objTable.Columns(1).Cells
Set objOriginalWordRange = objOriginalWord.Range
objOriginalWordRange.MoveEnd Unit:=wdCharacter, Count:=-1
Set objReplaceWordRange = objTable.Cell(nRowNumber, 2).Range
objReplaceWordRange.MoveEnd Unit:=wdCharacter, Count:=-1
AutoCorrect.Entries.Add Name:=objOriginalWordRange.Text, Value:=objReplaceWordRange.Text
nRowNumber = nRowNumber + 1
Next objOriginalWord
MsgBox ("All autocorrect items in the table1 are added.")
End Sub
It doesn't preserve any formatting: super- or subscripts, etc. Formatting autocorrect entries are stored in the Normal.dotm file and not in the regular .acl file so I haven't been able to figure out a way around this.
In a similar post, someone suggested a Find and Replace macro but Find and Replace doesn't allow me to replace with super- or subscripts.
There are two methods of adding Auto Correct Entries, Add and AddRichText. It is this second one that you use for formatted entries.
When faced with an issue like this my first resort is to check the Object Brower in the VBA editor (press F2 to display) to see what methods and properties may be available. My next step is to look them up in the VBA technical reference, aka Help, to check the usage.
If the problem is just sub/superscribt, then you could use uni-codes. Those are also available in autocorrect. Fx writing the unicodes ₁₂₃₄₅₆₇₈₉ instead of using formating on a normal 2. Most (but not all) characters exist in super and sub unicode.
The program is not working. It is giving an error message
Compile Error Expected Function or Variable
It is showing the following line as error
Autocorrect.Entries.Add Name:=objOriginalWordRange.Text, Value:=objReplaceWordRange.Text
Whenever I select a section of text in MS Word using this code:
Dim aRange As Range
Set aRange = ActiveDocument.Range( _
Start:=ActiveDocument.Paragraphs(1).Range.Start, _
End:=ActiveDocument.Paragraphs(3).Range.End)
aRange.Select
everything is fine except that Word automatically alters the selection to add a new line character at the end of the selection. How to avoid it? Perhaps it is possible to change the selection so that it will not include a new line character.
My question is similar to another one already asked, but I would like it to do it using VBA.
When you work with selections on the keyboard you use Shift + Left/Right Arrow keys to change the extent of the selection. In the Word object model there's an equivalent you can use with the Range object; actually, there's a set of methods: MoveStart, MoveEnd, MoveWhile, MoveUntil
In this case, you need the MoveEnd method. You can move the end point by a specific set of units, such as characters, words, paragraphs - you want to move by one character, going "backwards", so:
aRange.MoveEnd wdCharacter, -1
aRange.Select
This should work:
doc.Paragraphs(1).Range.Select
Selection.MoveEnd wdCharacter, -1
Selection.Copy
I have a Word document with various Bookmarks in it. Given specifications from a database, I loop through all of them and change the text of the range. In some cases I need to delete two lines above a bookmark. I believe this can be accomplished with a few lines of code, but I haven't been able to get anything to work. The closest I've gotten is the following:
Application.ActiveDocument.Bookmarks(1).Range.Sentences(1).Delete
In my project, I each bookmark range is only one line (one sentence). Since the two lines I want to delete are above the bookmark (and not in its range). How could I offset the Sentences member to allow me to do so?
Try this:
Sub DeletePrevTwoSentences()
Dim r As Word.Range
Set r = ActiveDocument.Bookmarks("TheBookmark").Range
Debug.Print r.start, r.end ' Just for testing
' Move the start of r back two sentences
r.MoveStart wdSentence, -2
' Move the end of r back one sentence
' Assumes the bookmark refers to an entire sentence that shouldn't get deleted
' Could also set end = start, then move end +2 sentences.
r.MoveEnd wdSentence, -1
Debug.Print r.start, r.end ' Just for testing
r.Delete
End Sub
Hope that helps
I have a document with a number of embedded hyperlinks to convert to plain hyperlinks. Whether they get pasted as clickable URLs or plaintext URLs doesn't matter, as long as it's actually displaying the URL.
For example, I need to change Microsoft Word to http://en.wikipedia.org/wiki/Microsoft_Word (either clickable or not).
In Word, if I select the hyperlink, right click, choose "copy hyperlink," then paste special, text only, I get the optimal result (non-clickable URL). If I record VBA code that does the exact same thing, the result is the original embedded link. I've played with various options: turning off smart paste, cut and paste, turning off autoformat of hyperlinks, changing the default paste options, but none of these change my end result.
Sub Replace_w_URLs()
'
' Replace_w_URLs Macro
'
'
Selection.NextField.Select
Selection.Range.Hyperlinks(1).Range.Fields(1).Result.Select
Selection.Copy
Selection.TypeBackspace
Selection.PasteSpecial Link:=False, DataType:=20, Placement:=wdInLine, _
DisplayAsIcon:=False
End Sub
The problem is likely the default behaviour of Word to add a hyperlink if it recognizes that the text you pasted is a URL. If you're doing this in a loop, it does the same thing as if you put the cursor at the end of the URL and hit the space-bar.
The easiest way to avoid this is to just operate on the hyperlink Ranges themselves and just change the text property. When you change HyperLink.Range.Text, it has the side effect of also removing the hyperlink at the same time.
Give this a shot:
Sub Replace_w_URLs()
Dim url As Range
Do While Selection.Hyperlinks.Count > 0
Set url = Hyperlinks(1).Range.Duplicate
url.Text = Hyperlinks(1).Address
Loop
End Sub
It should replace all of the hyperlinks in your Selection with the underlying URLs.
I have many word document with lots of bookmarks.
I use VBA code to change these bookmarks with data from a DB.
The problem is, sometimes the users need to edit these documents, and they tend to accidentally delete/change my bookmarks, which leads to the VBA code not recognizing the bookmark anymore.
So basically, what i'm wondering is how i can restrict users from editing my bookmarks in a word document.
I don't need a super secure solution, just enough protection so that the user knows that, "i should not touch this part".
Thanks in advance for your answer..
EDIT:
I was reading on different forums, and came across this,
http://social.msdn.microsoft.com/Forums/office/en-US/f70ca604-bbdb-4b5a-8363-f9e126105e91/writeprotection-of-bookmarks-in-word?forum=vsto
Which sort of does what i want. but was not able to implement/convert it to VBA code. Can someone also see how i maybe can use it?
Thanks again.
EDIT: office 2007 / 2010.
The following idea is tested for Word 2010. It should work for 2007 and 2013 as well but not for 2003.
I would suggest to use ContentControls (called CC further in the text) together with Bookmarks. Next, you will need to control one event which will check if user is selecting inside any of the ContentControl. If so, we will show the message and/or move selection outside protected area.
Step 1st. Each of your bookmarks should be enclosed inside RichText ContentControl. You could do it manually for selected bookmarks or you can run the following simple code to do it for all bookmarks inside your active document.
(Important assumption! there are not any other ContentControls in your document!)
Sub Add_Bookmark_CC()
Dim bookM As Bookmark
For Each bookM In ActiveDocument.Bookmarks
ActiveDocument.ContentControls.add wdContentControlRichText, bookM.Range
Next
End Sub
2nd step. We will control one event: Document_ContentControlOnEnter. Go to ThisDocument module in your Document VBAProject and create the following event (see some comments inside the code):
Private Sub Document_ContentControlOnEnter(ByVal ContentControl As ContentControl)
Debug.Print Now, ContentControl.Range.Bookmarks.Count
If ContentControl.Range.Bookmarks.Count > 0 Then
'Optional message box for user
MsgBox "There is bookmark inside this area which you should not change. " & _
vbNewLine & "You will be moved out of this range"
'optionam selection change right after CC area
Dim newPos As Long
newPos = ContentControl.Range.End + 2
ActiveDocument.Range(newPos, newPos).Select
End If
End Sub
Alternative for step 1st and 2nd. If you don't want to use CC event you could add CC to each bookmarks with CC content protection. In this situation you only need 1st step and the following sub:
Sub Add_Bookmark_CC_Protected()
Dim bookM As Bookmark
Dim CC As ContentControl
For Each bookM In ActiveDocument.Bookmarks
Set CC = ActiveDocument.ContentControls.add(wdContentControlRichText, bookM.Range)
CC.LockContents = True
Next
End Sub
Final! As you can see there are some more possible combination of steps 1 and 2.
The following code allows you to delete all CC if you need for any initial tests:
Sub Remove_All_CC()
Dim CC As ContentControl
For Each CC In ActiveDocument.ContentControls
CC.Delete
Next CC
End Sub
Protect your whole document using
'whole document readonly
ThisDocument.Protect Password:="password", NoReset:=False, Type:=wdAllowReadOnly
or
'only write in form fields (can't delete them, just fill them out)
ThisDocument.Protect Password:="mypassword", NoReset:=False, Type:=wdAllowOnlyFormFields
and now give some parts of the document free for editing:
ThisDocument.Bookmarks("myBookmark").Range.Editors.Add wdEditorEveryone
Selection.Range.Editors.Add wdEditorEveryone
Alternative
(not tested)
don't protect your whole document, just restrict the bookmarks you want to lock
ThisDocument.Bookmarks("myBookmark").Range.Editors.Add wdEditorOwners
or
ThisDocument.Bookmarks("myBookmark").Range.Editors.Add "abc#test.com"