2010-12-01 223 views
0

我對VBA非常新,剛剛學習。這是我的情況和問題:Word VBA「標籤未定義」如果存在書籤命令

1)我創建了一個工作的用戶窗體,其中包含鏈接到書籤的文本和組合框 2)問題是,如果某些書籤不存在,它將無法工作(並且項目需要這樣做:表單將需要運行在不是所有書籤都存在的文檔上) 3)如果書籤沒有在那裏,我希望表單不要給我提供錯誤消息,只需填寫那個特定的文檔中存在的那些文件 4)這裏是代碼:

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.ScreenUpdating = True 
    Unload Me 
End Sub 

4)我如何得到這個工作?????????

回答

0

我覺得你很接近。首先,避免Goto語句。在你的代碼中,很難說出你的意思。我認爲這些錯誤來自Goto聲明。它的參數是一個標籤,而不是行號。其次,避免使用End。最好有一個關閉程序。也就是說,代碼可以與任何數量的Exists語句一起使用。

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 

但是,請注意,每個找到的書籤都會完全替換文檔的內容,包括隨後發現的書籤。那是你的意思嗎?