View Single Post
 
Old 05-27-2021, 03:47 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,176
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

Just because docNameField is a variable within another sub doesn't make it available to other subs or functions. If you want the same variable to be used across different macros then you have two choices.
1. Use a function which takes in in the variable
Code:
'Code calling the function
str = docNameFieldPreview(docNameField)

'Note I've named the variable x here to avoid confusion. You can call it docNameField if you like but it is actually a different variable in this example.
Public Function docNameFieldPreview(x as String) As String
  docNameFieldPreview = ActiveDocument.MailMerge.DataSource.DataFields(x).Value
End Function
2. Declare it at the top of the module (outside of any sub/function) as either a Public or Private variable so the same name can be used anywhere in the module (if Private) or the template (if Public) eg.
Code:
Public docNameField as String  'this is empty until a macro gives it a value
Sub DoSomething()
  Dim str as string
  docNameField = "Name"
  str = docNameFieldPreview
  MsgBox str
End Sub
Public Function docNameFieldPreview() As String
  docNameFieldPreview = ActiveDocument.MailMerge.DataSource.DataFields(docNameField).Value
End Function
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote