none
How to use data from inputbox

    Question

  • I am using the following macro in MS Word to get data from the user via an InputBox.  How can I tehn deposit the contents of the variable "fname" into a form field on the parent document?

     

    <code>

    Sub Getinput()

    Dim fname

    fname = InputBox(Enter your name"

    End Sub

    </code>

     

    I tried using the name of the form field (text10) and adding this line:

    text10=fname

    and

    text10.text=fname

    to no avail.   I'm sure this must be something simple but alas I am a novice.

     

    Help?!

     

     

    Wednesday, July 26, 2006 7:09 PM

All replies

  • This should do it:

    Sub addData()

    ThisDocument.FormFields("Text1").Result = InputBox("Enter Name")

    End Sub

    ChasAA

    Wednesday, July 26, 2006 7:57 PM
  • Hi Jim,

    The reason why your code doesn't work is to do with a thing called scope. Variables have a scope in the sense that they are created (Dim x as string), they are used (x = "hello world"), and then they are destroyed (x = nothing). VBA and most other languages imply scope at different levels, one of these levels is at the procedural level. Basically once the sub of function has finished running all variables locally defined in the sub or function are destroyed.

    I'll use your sub to demonstrate

    Sub Getinput()

    Dim fname    'here you create your variable fname

    fname = InputBox(Enter your name"    'here you use your variable

    End Sub   'once the sub completes all variables defines in the sub (fname) are destroyed

     

    If you then wrote another sub to display the variable then you will have errors as the variable is out of scope, it has been destroyed.

    Sub DisplayInput()

    Msgbox fname     'cannot use fname as it's out of scope

    End Sub

     

    In this scenaro you would need to do this.... fname has a higher scope and is available to both the subprocedures.

    Dim fname as String

    Sub Getinput()

    fname = InputBox(Enter your name"

    End Sub

    Sub DisplayInput()

    Msgbox fname  

    End Sub

    Thursday, July 27, 2006 8:57 AM