MS Access VBA - создание Word Do c работает только один раз - PullRequest
0 голосов
/ 06 августа 2020

У меня есть база данных Access с формой, которая отображает информацию о записи в базе данных. Я добавил кнопку, которая открывает новый документ Word (используя созданный мною шаблон), а затем берет соответствующие поля из формы и добавляет их в документ Word в соответствующих местах (отмеченных закладками). Он работает точно так, как предполагалось в первый раз в экземпляре Access, но он не будет работать снова, пока я не закрою базу данных полностью и не начну заново. Есть предложения, почему он работает только в первый раз?

Private Sub PPPGenerate_Click()
    
    Dim namestr, unionstr, employerstr, countystr, emailstr, phonestr, issuestr As String 'create the variables which will be populated with the corresponding information from the record displayed on the form
    namestr = Me.First + " " + Me.Last
    titlestr = Me.title
    REM All records have first and last name, and title, so we can initialize those without checking for null values
    
    If Not IsNull(Me.Employer) Then 'If this record has a value for Employer, put it in the variable. Otherwise, use a filler
        employerstr = Me.Employer
    Else 'If we don't know who the employer is
        employerstr = "(Not Known)"
    End If
    
    
    If Not IsNull(Me.County) Then 'If this record has a value for County, put it in the variable. Otherwise, use a filler
        countystr = Me.County
    Else
        countystr = "(Not Known)"
    End If
    
    
    If Not IsNull(Me.Email) Then 'If this record has a value for Email, put it in the variable. Otherwise, use a filler
        emailstr = Me.Email
    Else
        emailstr = "(Not Known)"
    End If
    

    If Not IsNull(Me.Home_Phone) Then 'If this record has a value for Phone, put it in the variable. Otherwise, use a filler
        phonestr = Me.Home_Phone
    ElseIf Not IsNull(Me.Cell_Phone) Then
        phonestr = Me.Cell_Phone
    ElseIf Not IsNull(Me.Work_Phone) Then
        phonestr = Me.Work_Phone
    Else
        phonestr = "(Not Known)"
    End If
    

    If Not IsNull(Me.Notes) Then 'If this record has a value for Notes, put it in the variable. Otherwise, use a filler
        issuestr = Me.Notes
    Else
        issuestr = "No notes on this person."
    End If
    

    Dim Wrd As New Word.Application 'create a new word doc based on the template
    Dim doc As Word.Document
    Set Wrd = CreateObject("Word.Application")
    Dim MergeDoc As String
    MergeDoc = Application.CurrentProject.Path
    MergeDoc = MergeDoc + "\PPP.dotx" 'The Template
    Set doc = Wrd.Documents.Add(MergeDoc)
    Wrd.Visible = True
    With Word.ActiveDocument.Bookmarks 'put the variables into the word doc
        .Item("FullName").Range.Text = namestr
        .Item("title").Range.Text = titlestr
        .Item("EmployedAt").Range.Text = employerstr
        .Item("County").Range.Text = countystr
        .Item("emailaddress").Range.Text = emailstr
        .Item("phonenumber").Range.Text = phonestr
        .Item("IssueDescription").Range.Text = issuestr
    End With
    
End Sub

Ответы [ 2 ]

2 голосов
/ 06 августа 2020
With Word.ActiveDocument.Bookmarks   'note Word/Wrd 

действительно должно быть

With doc.Bookmarks

... поскольку у вас есть ссылка на объект документа.

К вашему сведению, вот полезная служебная функция, когда у вас есть куча " если не это, то то «сделать:

'Return the first non-null/non-zero-length argument
Function Prefer(ParamArray intVals() As Variant) As Variant
    Dim i As Long, val
    For i = LBound(intVals()) To UBound(intVals())
        val = intVals(i)
        If Not IsNull(val) Then
            If Len(val) > 0 Then Exit For
        End If
    Next i
    Prefer = val
End Function

, чтобы вы могли сделать это:

employerstr = Prefer(Me.Employer, "(Not Known)")
'...
phonestr = Prefer(Me.Home_Phone, Me.Cell_Phone, Me.Work_Phone, "(Not Known)")

вместо

If Not IsNull(Me.Home_Phone) Then 
    phonestr = Me.Home_Phone
ElseIf Not IsNull(Me.Cell_Phone) Then
    phonestr = Me.Cell_Phone
ElseIf Not IsNull(Me.Work_Phone) Then
    phonestr = Me.Work_Phone
Else
    phonestr = "(Not Known)"
End If
0 голосов
/ 06 августа 2020

Возможное решение :

Изменения отмечены '**

Private Sub PPPGenerate_Click()
    
    '** Explicitly declare each variable as  a String
    Dim namestr As String, unionstr As String, employerstr As String, countystr As String, emailstr As String, phonestr As String, issuestr As String 'create the variables which will be populated with the corresponding information from the record displayed on the form
    namestr = Me.First + " " + Me.Last
    titlestr = Me.Title
    Rem All records have first and last name, and title, so we can initialize those without checking for null values
    
    If Not IsNull(Me.Employer) Then 'If this record has a value for Employer, put it in the variable. Otherwise, use a filler
        employerstr = Me.Employer
    Else 'If we don't know who the employer is
        employerstr = "(Not Known)"
    End If
    
    
    If Not IsNull(Me.County) Then 'If this record has a value for County, put it in the variable. Otherwise, use a filler
        countystr = Me.County
    Else
        countystr = "(Not Known)"
    End If
    
    
    If Not IsNull(Me.Email) Then 'If this record has a value for Email, put it in the variable. Otherwise, use a filler
        emailstr = Me.Email
    Else
        emailstr = "(Not Known)"
    End If
    

    If Not IsNull(Me.Home_Phone) Then 'If this record has a value for Phone, put it in the variable. Otherwise, use a filler
        phonestr = Me.Home_Phone
    ElseIf Not IsNull(Me.Cell_Phone) Then
        phonestr = Me.Cell_Phone
    ElseIf Not IsNull(Me.Work_Phone) Then
        phonestr = Me.Work_Phone
    Else
        phonestr = "(Not Known)"
    End If
    

    If Not IsNull(Me.Notes) Then 'If this record has a value for Notes, put it in the variable. Otherwise, use a filler
        issuestr = Me.Notes
    Else
        issuestr = "No notes on this person."
    End If
    
    '** removed New keyword
    Dim Wrd As Word.Application 'create a new word doc based on the template
    Dim doc As Word.Document
    
    '** try to get existing word app first
    On Error Resume Next
    Set Wrd = GetObject(, "Word.Application")
    If Wrd Is Nothing Then
        Set Wrd = New Word.Application
    End If
    On Error GoTo 0
    
    Dim MergeDoc As String
    MergeDoc = Application.CurrentProject.Path
    MergeDoc = MergeDoc + "\PPP.dotx" 'The Template
    Set doc = Wrd.Documents.Add(MergeDoc)
    Wrd.Visible = True
    '** changed Word.ActiveDocument to doc
    With doc.Bookmarks 'put the variables into the word doc
        .Item("FullName").Range.Text = namestr
        .Item("title").Range.Text = titlestr
        .Item("EmployedAt").Range.Text = employerstr
        .Item("County").Range.Text = countystr
        .Item("emailaddress").Range.Text = emailstr
        .Item("phonenumber").Range.Text = phonestr
        .Item("IssueDescription").Range.Text = issuestr
    End With
    
End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...