Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

VB Function result as the value of a Formula Field

Status
Not open for further replies.

wgcs

Programmer
Mar 31, 2002
2,056
EC
Is it possible to insert a field in a word document that will display the result of a VBA function call?

I want a custom summary of only certain rows at the bottom of a table: It would be easy to write a simple macro to identify the rows based on text in an adjacent column, but the hard part is getting the total into the proper cell at the bottom of the table.

I could hard-code the cell coordinates, which is bad (because more rows may be added).

I could hard-code the cell coordinates based off of the total rows minus X, which is better (but still kinda fixes the document layout).

I could use bookmarks, and insert the result at the bookmark (I'm not very familiar yet with manipulating bookmarks)

Or, my preference, I could insert a field at the right spot, that calls the macro/VBA function with the proper parameters, and displays the result... but Can I?
 
Either of the last two solutions could be used alone or in combination, but both suffer from the risk that the bookmark and/or (macrobutton) field might be deleted before the macro is run.

A macrobutton field can certainly fire your macro, but you'd probably want to keep it in a different cell to the one you want to put your result in - unless you wanted to this to be a once-only solution that replaces the macrobutton field. The other cell would simply hold the bookmark for updating.

For example, you might code a macrobutton field as:
{MACROBUTTON MyMacro Click Here"}
Clicking on this field would fire the macro 'My Macro', which you could use to do the calculation. Then, to update the bookmark with your result, you'd call a macro that takes parameters (sBookmark for the bookmark's name and sValue for the result to display) like the following:

Code:
Sub UpdateBookmark (sBookmark as string, sValue as string)
Dim oRange as Range
If ActiveDocument.Bookmarks.Exist (sBookmark) then
    Set oRange = ActiveDocument.Bookmarks(sBookmark).Range
    oRange.Text = sValue
    ActiveDocuments.Bookmarks.Add sBookmark, oRange
Else
    MsgBox "Bookmark " & sBookmark & " not found."
End if
Set oRange = Nothing
End sub

Cheers

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top