且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串太长,将数据从Excel复制到Word文档中

更新时间:2023-12-04 13:40:34

Greg Maxey(Word VBA MVP)提供了一些您可能会发现有用的提示.

Greg Maxey (Word VBA MVP) has some tips you might find useful.

http://gregmaxey.com/word_tip_pages/find_replace_long_string.html

Replacement.Text的字符数限制为255个字符,因此您必须使用On Error Resume Next忽略它(删除此行,您将看到类似以下的错误).

There is a 255-character limit on the Replacement.Text, so you must be ignoring this with an On Error Resume Next (get rid of this line, and you'll see the error like below).

他的建议是利用剪贴板,只要您只在Word文档之间或在Word文档中(例如,对.Copy范围或选择)进行操作,但可以从其他应用程序(如Excel)进行操作,剪贴板就可以很好地工作,我认为您可能需要使用MsForms.DataObject作为中介,将文本放入剪贴板,然后才能使用他概述的技巧.

His suggestion is to leverage the Clipboard, which works fine as long as you're only doing stuff between Word documents or within a Word document (e.g., to .Copy a range or selection), but from other application like Excel, I think you'll probably need to use an MsForms.DataObject as an intermediary to put the text in the clipboard, before you can use the trick he outlined.

类似的东西:

Const wdReplaceAll As Long = 2
Const wdFindContinue As Long = 1
Dim longString As String
Dim wd As Object, doc As Object, sel As Object
Dim dataObj As New DataObject  '## Requires reference to MSForms
'## Alternatively:
' Dim dataObj as Object
' Set dataObj = CreateObject("MSForms.DataObject")

Set wd = GetObject(, "Word.Application")
Set doc = wd.ActiveDocument

longString = Worksheets("3A- Multi-Family Housing").Range("A4").value

dataObj.SetText longString
dataObj.PutInClipboard

Set sel = doc.Range
sel.Select

With doc.Range.Find
    .ClearFormatting
    .Text = "[[3A Description]]"
    .Replacement.ClearFormatting
    .Replacement.Text = "^c"
    .Execute Replace:=wdReplaceAll, Forward:=True, _
        Wrap:=wdFindContinue
End With