字符串太长,将数据从Excel复制到Word文档中
我正在尝试用Excel单元格中的字符串替换文本文档中的占位符.
I'm trying to replace a placeholder in a text document with a string from an Excel cell.
它对于少于255个字符的字符串有效,但对于大于255个字符的字符串则无效.
It works fine for strings less than 255 characters but not when they are greater.
代码:
Sub Sheet003ADes()
'Sheet 3A- Multi-Family Housing -----------------------------
With Selection.Find
.ClearFormatting
.Text = "[[3A DESCRIPTION]]"
.Replacement.ClearFormatting
.Replacement.Text = Worksheets("3A- Multi-Family Housing").Range("A4").Value 'Insert 3A Activity Description
.Execute Replace:=wdReplaceAll, Forward:=True, _
Wrap:=wdFindContinue
End With
End Sub
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