Word VBA "Label Not Defined" If Bookmark exists command
I am very new to VBA and just learning. Here's my situation and problem:
1) I created a working userform with text and comboboxes linking to bookmarks 2) Problem is that it doesn't work if some bookmarks don't exist (and the project will require this: the form will need to run on documents where not all bookmarks are present) 3) I would like the form stop giving me error messages if bookmarks arent there and just fill out the ones that are existing in that particular ocument 4) Here's the Code:
Private Sub cmdOK_Click()
Application.ScreenUpdating = False
With ActiveDocument
If .Bookmarks.Exists("cboYourName") Then
.Range.Text = cboYourName.Value
Else: GoTo 28
End If
If .Bookmarks.Exists("cboYourPhone") Then
.Range.Text = cboYourPhone.Value
Else: GoTo 32
End If
If .Bookmarks.Exists("cboYourFax") Then
.Range.Text = cboYourFax.Value
Else: GoTo 36
End If
If .Bookmarks.Exists("cboYourEmail") Then
.Range.Text = cboYourEmail.Value
Else: GoTo 40
End If
If .Bookmarks.Exists("txtContractName") Then
.Range.Text = txtContractName.Value
Else: GoTo 44
End If
If .Bookmarks.Exists("txtContractNumber") Then
.Range.Text = txtContractNumber.Value
Else: End
End If
End With
Application.ScreenUpdatin开发者_如何学Gog = True
Unload Me
End Sub
4) How do I get this to work?????????
I think you're close. First, avoid Goto statements. In your code, it's hard to tell what you mean to do. I think the errors are from the Goto statements. Its parameter is a label, not a line number. Second, avoid using End. It's better to have a closing routine. That said, the code works with any number of Exists statements.
Private Sub cmdOK_Click()
Application.ScreenUpdating = False
With ActiveDocument
If .Bookmarks.Exists("cboYourName") Then
.Range.Text = "cboYourName text."
Else
Debug.Print "Bookmark exists."
End If
If .Bookmarks.Exists("cboYourPhone") Then
.Range.Text = "cboYourPhone text"
Else
Debug.Print "Bookmark does not exists."
End If
End With
Application.ScreenUpdating = True
Unload Me
End Sub
However, be aware that each found bookmark completely replaces the content of the document, including subsequently found bookmarks. Is that what you mean to do?
精彩评论