How to delete a text in a table cell when a specific word is found - vba

In my code below, when the word isn't there, all the table contente is deleted. How to fix it? Text is in Cell(1,1) for multiple tables.
Sub DeleteText()
StartWord = "Orientation:"
For Each oTbl In ActiveDocument.Tables
Set oRng = oTbl.Range
With oRng
.Find.Execute Findtext:=StartWord & "*", MatchWildcards:=True
.MoveStart wdCharacter, 0
.MoveEndUntil vbCr
.Delete
End With
Next
End Sub

First of all you need to add if statement which will check if your text is found. You will find that in the code below. However, I also improved the way you delete the whole content of cell where your text is found. My solution is better in situation when you have more lines/paragraphs/sentences in the cell.
Sub DeleteText_Improved()
Dim StartWord As String
Dim oTbl As Table
Dim oRng As Range
StartWord = "Mauris"
For Each oTbl In ActiveDocument.Tables
Set oRng = oTbl.Range
With oRng
.Find.Execute Findtext:=StartWord & "*", MatchWildcards:=True
If .Find.Found Then
'how to select whole cell range
oTbl.Cell(.Information(wdEndOfRangeRowNumber), _
.Information(wdEndOfRangeColumnNumber)).Range.Delete
End If
End With
Next
End Sub
Final remark- your code is working only for the first occurrence of the word you search for. It will not remove other cells where the word appears.

Related

How to delete ALL empty paragraphs only at the START of a Word file

I am trying to delete ALL empty paragraphs at the start of a Word file. I am using the following to delete just the FIRST paragraph but I need to delete all empty paragraphs in a row, so that if you have 5 empty lines, they will all be deleted.
here is the code:
Dim MyRange As Range
Set MyRange = ActiveDocument.Paragraphs(1).Range
If MyRange.Text = vbCr Then MyRange.Delete
I've tried adding a loop and for statement, but to no avail.
thanks in advance.
Collapse to the start of the document, then extend the range whilst 'empty characters' are found.
Here is your starter for 10
Dim MyRange As Range
Set MyRange = ActiveDocument.Paragraphs(1).Range
MyRange.Collapse direction:=wdCollapseStart
MyRange.MoveEndWhile cset:=" " & vbCrLf ' & any other invisible characters that may be present
MyRange.Delete
Each paragraph must have at least one character - the paragraph mark itself. So all we need to do is to check if the paragraph contains only 1 character.
Simple like this:
Sub ClearEmptyPargraphAtStartOfDocument()
While (ActiveDocument.Paragraphs(1).Range.Characters.Count = 1)
ActiveDocument.Paragraphs(1).Range.Delete
Wend
End Sub
This seems to work for me
Public Sub SOCheck()
Dim MyRange As Range, CarryOn As Boolean
CarryOn = True
While CarryOn
Set MyRange = ActiveDocument.Paragraphs(1).Range
If MyRange.Text = vbCr Then
MyRange.Delete
Else
CarryOn = False
End If
Wend
'MsgBox "Done"
End Sub
It's just a loop around your own code

Add a number of tables to a bookmark in Word VBA while maintaining and expanding the bookmark

I'm trying to create some automation using Word VBA and looking for some advice.
I have a bookmark in a document. What I want to do is call some VBA that goes to that bookmark and creates a number of tables, could be 1, could be 50 depending on some variables.
I would like to maintain that bookmark so that it covers the entirety of that new section of tables so that if someone runs the macro again, the tables are dropped and recreated nicely.
So far I have some code that creates the tables at the bookmark and recreates it but it seems to be creating the bookmark in the first cell as the tables nest.
Can anybody help me?
Private Sub InsertTableInBookmark(BookmarkName As String)
Debug.Print "[INFO] Started Private Sub InsertTableInBookmark"
Dim objRng As Range
Dim objTable As Table
Selection.GoTo what:=wdGoToBookmark, Name:=BookmarkName
Selection.Expand wdParagraph
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=9, NumColumns:=4, DefaultTableBehavior:=wdWord9TableBehavior
ActiveDocument.Bookmarks.Add BookmarkName, Selection.Range
Debug.Print "[INFO] Finished Private Sub InsertTableInBookmark"
End Sub
Thanks.
Try:
Private Sub InsertTableInBookmark(BmkNm As String, t As Long)
Dim i As Long, BmkRng As Range, Tbl As Table
With ActiveDocument
If .Bookmarks.Exists(BmkNm) Then
Set BmkRng = .Bookmarks(BmkNm).Range
For i = 1 To t
Set Tbl = .Tables.Add(Range:=BmkRng.Characters.Last, _
NumRows:=9, NumColumns:=4, DefaultTableBehavior:=wdWord9TableBehavior)
With BmkRng
.End = Tbl.Range.End
If i < t Then
.Characters.Last.Next.InsertBefore vbCr & vbCr
.End = .End + 2
End If
End With
Next
.Bookmarks.Add BmkNm, BmkRng
End If
End With
Set BmkRng = Nothing
End Sub
Note that I've added another parameter to the sub - t - for the number of tables to insert.

How to refer to a line or table row I've just inserted

I feel I must be missing something obvious. I'm using VBA to build a Word document by writing lines to it one at a time. Once I've written a line, I need to format it - this could be bolding, setting tabstops, etc. But in order to format a line, I have to be able to refer to it. All the formatting facilities operate on a Range or a Selection - how do I identify the line I've just inserted as the Range I want to operate on? (Also, same question for table rows, as the doc also includes tables I'm building one row at a time, and I need to format cells as I go).
This is how to insert text and format it as you go, using a Range object. It's better to not try to simulate how a user works by using Selection and TypeText. The code runs more slowly and it's more difficult to work precisely. There can be only one Selection, but code can work with many Ranges...
The other important point to remember is to declare and instantiate objects as they're created - tables and table rows, for example.
Dim rng1 as Word.Range, rng2 as Word.Range
Set rng1 = ActiveDocument.Content
rng1.Text = "line one" & vbCr
rng1.Font.Bold = True
rng1.Collapse wdCollapseEnd
rng1.Text = "line two" & vbCr
rng1.Font.Bold = False
rng1.Collapse wdCollapseEnd
Set rng2 = rng1.Duplicate
rng2.Text = "line three" & vbCr
rng2.Font.Italic = True
'You can still work with the first range
rng1.ParagraphFormat.Alignment = wdAlignParagraphCenter
'
Dim tbl as Word.Table, rw1 as Word.Row, rw2 as Word.Row
Set tbl = ActiveDocument.Tables.Add
Set rw1 = tbl.Rows(1)
Set r2 = tbl.Rows.Add
Sub FormatBold()
Dim StartWord As String, EndWord As String
StartWord = "STARTSTART"
EndWord = "ENDEND"
With ActiveDocument.Content.Duplicate
.Find.Execute Findtext:=StartWord & "*" & EndWord, MatchWildcards:=True
.MoveStart wdCharacter, Len(StartWord)
.MoveEnd wdCharacter, -Len(EndWord)
.Font.Bold = True ' Or whatever you want to do
End With
End Sub
Format the text while you write it:
Sub StartTyping()
Selection.TypeText Text:="This is the "
Selection.Font.Bold = wdToggle
Selection.TypeText Text:="sentence"
Selection.Font.Bold = wdToggle
Selection.TypeText Text:=" I am inserting." & vbCr
End Sub

Macro to insert comments on keywords in selected text in a Word doc?

I'm new to VBA and would greatly appreciate some help on a problem.
I have long Word documents where I need to apply standard comments to the same set of keywords, but only in selected sections of the document. The following macro worked to find a keyword and apply a comment (from question here https://superuser.com/questions/547710/macro-to-insert-comment-bubbles-in-microsoft-word):
Sub label_items()
'
' label_items Macro
'
'
Do While Selection.Find.Execute("keyword1") = True
ActiveDocument.Comments.Add range:=Selection.range, Text:="comment for keyword 1"
Loop
End Sub
The two modifications are:
1) only apply the comments to user selected text, not the whole document. I tried a "With Selection.Range.Find" approach but I don't think comments can be added this way (??)
2) repeat this for 20+ keywords in the selected text. The keywords aren't totally standard and have names like P_1HAI10, P_1HAI20, P_2HAI60, P_HFS10, etc.
EDIT: I have tried to combine code from similar questions ( Word VBA: finding a set of words and inserting predefined comments and Word macro, storing the current selection (VBA)) but my current attempt (below) only runs for the first keyword and comment and runs over the entire document, not just the text I have highlighted/selected.
Sub label_items()
'
' label_items Macro
'
Dim selbkup As range
Set selbkup = ActiveDocument.range(Selection.range.Start, Selection.range.End)
Set range = selbkup
Do While range.Find.Execute("keyword 1") = True
ActiveDocument.Comments.Add range, "comment for keyword 1"
Loop
Set range = selbkup
Do While range.Find.Execute("keyword 2") = True
ActiveDocument.Comments.Add range, "comment for keyword 2"
Loop
'I would repeat this process for all of my keywords
End Sub
I've combed through previous questions and the Office Dev Center and am stuck. Any help/guidance is greatly appreciated!
It's a matter of adding a loop and a means of Finding the next keyword you're looking for. There are a few suggestions in the code example below, so please adjust it as necessary to fit your requirements.
Option Explicit
Sub label_items()
Dim myDoc As Document
Dim targetRange As Range
Set myDoc = ActiveDocument
Set targetRange = Selection.Range
'--- drop a bookmark to return the cursor to it's original location
Const RETURN_BM = "OrigCursorLoc"
myDoc.Bookmarks.Add Name:=RETURN_BM, Range:=Selection.Range
'--- if nothing is selected, then search the whole document
If Selection.Start = Selection.End Then
Selection.Start = 0
targetRange.Start = 0
targetRange.End = myDoc.Range.End
End If
'--- build list of keywords to search
Dim keywords() As String
keywords = Split("SMS,HTTP,SMTP", ",", , vbTextCompare)
'--- search for all keywords within the user selected range
Dim i As Long
For i = 0 To UBound(keywords)
'--- set the cursor back to the beginning of the
' originally selected range
Selection.GoTo What:=wdGoToBookmark, Name:=RETURN_BM
Do
With Selection.Find
.Forward = True
.Wrap = wdFindStop
.Text = keywords(i)
.Execute
If .Found Then
If (Selection.Start < targetRange.End) Then
Selection.Comments.Add Selection.Range, _
Text:="Found the " & keywords(i) & " keyword"
Else
Exit Do
End If
Else
Exit Do
End If
End With
Loop
Next i
'--- set the cursor back to the beginning of the
' originally selected range
Selection.GoTo What:=wdGoToBookmark, Name:=RETURN_BM
End Sub

Microsoft Word 2007 VBA - Find the paragraph immediately following a table?

I have a VBA macro in Microsoft Word 2007 that finds all tables in my document with a particular background shade color and then deletes that table. That part works fine.
But, in addition to needing to delete the table, I also need to delete the paragraph that follows it. The paragraph that ALWAYS follows is of style "Macro Text" with no text in it. It is there simply to "break up the tables" from each other so that they don't combine into one large table.
How would I do this? Following is my code for deleting the tables:
For Each aTable In ActiveDocument.Tables
If aTable.Rows(1).Cells(2).Shading.BackgroundPatternColor = wdColorGray15 Then
aTable.Delete
End If
Next aTable
At its simplest I think you need something like this. You may need to extend the range to include the entire paragraph, check the style name etc.
Dim aTable As Word.Table
Dim rng As Word.Range
For Each aTable In ActiveDocument.Tables
If aTable.Rows(1).Cells(2).Shading.BackgroundPatternColor = wdColorGray15 Then
Set rng = aTable.Range
rng.Move unit:=wdParagraph, Count:=1
aTable.Delete
rng.Delete
Set rng = Nothing
End If
Next aTable
THANKS bibadia! You saved me!
Correct answer (for finding grey text in either column of two column tables in ALL tables and then deleting those tables):
Dim aTable As Word.Table
Dim rng As Word.Range
For Each aTable In ActiveDocument.Tables
If aTable.Shading.BackgroundPatternColor = wdColorGray15 Then
Set rng = aTable.Range
rng.Move unit:=wdParagraph, Count:=1
aTable.Delete
rng.Delete
Set rng = Nothing
Else
If aTable.Rows(1).Cells(2).Shading.BackgroundPatternColor = wdColorGray15 Then
Set rng = aTable.Range
rng.Move unit:=wdParagraph, Count:=1
aTable.Delete
rng.Delete
Set rng = Nothing
End If
End If
Next aTable