如何解决从Access到Word传递的FormFields VBA的字符限制

时间:2019-02-13 13:00:40

标签: vba ms-access ms-word

我正在尝试将Access表单中字段的内容传递给Word文档,该文档使用以下代码完全满足我的需要,但其中一个字段存在一个小问题。

.FormFields("txtReasonforReward").Result = Me![Reason for Reward]

在达到字符数限制时,我遇到了一些问题。

我已经看到了一些有关如何避免这种情况的示例,但是我不确定它们在我的基本代码中如何工作。目前,我对VBA的理解有些不足,因此请您提出任何清晰的防白痴建议。

请有人告诉我如何进行操作。

Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set doc = objWord.Documents.Open(***path to file***, , True)
With doc
.FormFields("txtFirstName").Result = Me![First Name]
.FormFields("txtLastName").Result = Me![Last Name]
.FormFields("txtReasonforReward").Result = Me![Reason for Reward]
.FormFields("txtCompanyValue").Result = Me![Company Value]
.FormFields("txtRequestingManager").Result = Me![Requesting Manager]
.FormFields("txtLocation").Result = Me![Location]
.FormFields("txtJobTitle").Result = Me![Job Title]
.FormFields("txtReqMgrJobTitle").Result = Me![Requesting Manager Job Title]
.FormFields("txtMonetaryValue").Result = Me![MoneyCalculated]
.FormFields("txtDesc").Result = Me![Description]
.FormFields("txtPayroll").Result = Me![Payroll Number]
.FormFields("txtGrade").Result = Me![Grade]
.FormFields("txtLocation2").Result = Me![Location]
.FormFields("txtRequestingMgr").Result = Me![Requesting Manager]
.FormFields("txtLevelofAction").Result = Me![ValueofPayment]
.FormFields("txtGemNom").Result = Me![GemNomination]
.FormFields("txtHRID").Result = Me![ID]
.FormFields("txtPeriod").Result = Me![Period]

.Visible = True
.Activate

End With

objWord.View.ReadingLayout = True

1 个答案:

答案 0 :(得分:1)

Word有许多可能的对象可用作“数据目标”,其中表单字段是其中之一。书签和内容控件是附加的(但不是唯一的)可能性。

在这种情况下,我建议将数据写入Bookmark,因为表单字段也是书签-无需更改目标文档。这将避免255个字符的限制,这是由于表单字段而不是Word引起的。

为了在作为表单保护的文档(似乎是这样)中写书签,有必要删除表单保护。可以重新写入数据。这样做可能是一个好主意,因为否则表单字段可能会重置,这将丢失写入其中的数据。那样,或者将书签技术全面应用,而不是仅应用于一个数据目标。

'Add objects to the declarations
Dim rng As Word.Range
Dim x As String

'Do things...

.FormFields("txtHRID").Result = Me![ID]
.FormFields("txtPeriod").Result = Me![Period]

'After writing to the form fields, add the long string of data
If doc.ProtectionType <> wdNoProtection Then
   doc.Unprotect
End If
'Get the range of the form field, based on its name
Set rng = doc.Bookmarks("txtReasonforReward").Range
'Move the starting point back one character so that the form field can be deleted. 
rng.MoveStart wdCharacter, -1
'Be sure to save this character as the deletion will remove it
x = rng.Characters.First
rng.FormFields(1).Delete
'Assign the value
rng.Text = x & Me![Reason for Reward]
'Re-instate document protection
doc.Protect wdAllowOnlyFormFields, True
相关问题