PDA

View Full Version : [SOLVED:] Word VBA: Manipulating table data and deleting bookmarks



ajhez
05-12-2015, 08:08 AM
Hi all

I am currently working on creating a word document containing a table which is populated by data from an excel sheet.

I have managed to figure out how to get the various data over from excel into word, but the next stage is to run a macro that essentially cleans up the word document by removing text that is not necessary based on the data carried over from the excel sheet.

The word document contains a table at the begging (with the 2nd column being populated by the data from the excel sheet) underneath the table there are paragraphs of text relating to the data in each row of the table. However, where the data inputted from the excel sheet = 0 then i want to delete the related paragraph of text from the document.

So far i have individually bookmarked the entire range of each of theparagraphs i want to delete. Ideally what i want to do is 'if the data/text in row 1 column 2 = "0" then delete 'bookmark x' if it is anything else then i want it to keep the paragraph as normal.

Below is what i've tried so far (apologies for the basic nature of it):


Sub BTest()
Dim bnName As Range
Set bnName = ActiveDocument.Bookmarks("bmName").Range
If ActiveDocument.Tables(1).Cell(1, 2).Range.Text = "0" Then
ActiveDocument.Bookmarks("bmName").Range.Delete
Else
End If
End Sub


Any ideas? Thanks all!

gmayor
05-12-2015, 10:48 PM
You are almost there, however you need to exclude the cell end character from the cell range text or you will never have a text value of "0". Also having named the bookmark as a range, then use the name later in the macro to delete the range.


Dim oBMName As Range 'Use a name that doesn't conflict with your bookmark name
Dim oCell As Range
'Define the bookmark range
Set oBMName = ActiveDocument.Bookmarks("bmName").Range
'Define the cell range to evaluate
Set oCell = ActiveDocument.Tables(1).Cell(1, 2).Range
'Remove the cell end character from the range
oCell.End = oCell.End - 1
'Check the range text content
If oCell.Text = "0" Then
'Set the range text to nothing
oBMName.Text = ""
'Reassign the bookmark to the empty range (in case you need it later)
ActiveDocument.Bookmarks.Add "bmName", oBMName
End If

ajhez
05-13-2015, 02:24 AM
Thanks so much for this quick and excellent response! It works an absolute treat.

Thanks again for your time and expertise!