View Single Post
 
Old 07-25-2016, 12:34 AM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2016
Expert
 
Join Date: Aug 2014
Posts: 4,103
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

If you want the code to work when you create a new document, it should be in the template and be called AutoNew and not AutoOpen. If you want it to run when you open the document the code should be in the document (unless you are certain that the document will always be able to access the template) and the document saved as macro enabled.

Frankly I wouldn't use an active X text box for this. Better to use a docvariable, a content control or a bookmark. The following provides all the suggested options

Code:
Sub AutoOpen()

Dim MyDoc As Document
Dim strQuotes(15) As String
Dim lngIndex As Long
Dim oRng As Range
    Set MyDoc = Application.ActiveDocument

    strQuotes(0) = "'Quote 1'"
    strQuotes(1) = "'Quote 2'"
    strQuotes(2) = "'Quote 3'"
    strQuotes(3) = "'Quote 4'"
    strQuotes(4) = "'Quote 5'"
    strQuotes(5) = "'Quote 6'"
    strQuotes(6) = "'Quote 7'"
    strQuotes(7) = "'Quote 8'"
    strQuotes(8) = "'Quote 9'"
    strQuotes(9) = "'Quote 10'"
    strQuotes(10) = "'Quote 11'"
    strQuotes(11) = "'Quote 12'"
    strQuotes(12) = "'Quote 13'"
    strQuotes(13) = "'Quote 14'"
    strQuotes(14) = "'Quote 15'"
    strQuotes(15) = "'Quote 16'"

    lngIndex = Int((16) * Rnd)
    'MyDoc.tbRandomQuote.Text = strQuotes(lngIndex) 'Activex text box
    'MyDoc.SelectContentControlsByTitle("tbRandomQuote").Item(1).Range.Text = strQuotes(lngIndex) 'content control
    'MyDoc.Variables("tbRandomQuote").Value = strQuotes(lngIndex) 'docvariable - reproduce with docvariable field
    'MyDoc.Fields.Update 'update the docvariable field
    FillBM "tbRandomQuote", strQuotes(lngIndex)
    
End Sub

Private Sub FillBM(strBMName As String, strValue As String)
'Graham Mayor
Dim oRng As Range
    With ActiveDocument
        On Error GoTo lbl_Exit
        Set oRng = .Bookmarks(strBMName).Range
        oRng.Text = strValue
        oRng.Bookmarks.Add strBMName
    End With
lbl_Exit:
    Set oRng = Nothing
    Exit Sub
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote