将多行字符串从Excel传递到Word
我目前正在尝试将多行字符串从Excel传递到Word文档。我首先使用单元格数据创建字符串,然后尝试通过搜索和替换的方法将其传递给Word。代码在word中查找单词(替换的位置),但用空字符串替换。从这件事中得到一些东西;首先,I将多行字符串从Excel传递到Word,excel,vba,ms-word,Excel,Vba,Ms Word,我目前正在尝试将多行字符串从Excel传递到Word文档。我首先使用单元格数据创建字符串,然后尝试通过搜索和替换的方法将其传递给Word。代码在word中查找单词(替换的位置),但用空字符串替换。从这件事中得到一些东西;首先,IDebug.Print替换发生时字符串,并且立即窗口中的字符串已满。其次,当我用一个简单的字符串替换单词时,它会很好地替换它,这让我相信我试图发送给word的多行字符串似乎有问题。下面是我的代码和其他可能相关的内容 下面是循环遍历每个工作表并为每个工作表创建相关字符串的每
Debug.Print
替换发生时字符串,并且立即窗口中的字符串已满。其次,当我用一个简单的字符串替换单词时,它会很好地替换它,这让我相信我试图发送给word的多行字符串似乎有问题。下面是我的代码和其他可能相关的内容
下面是循环遍历每个工作表并为每个工作表创建相关字符串的每个循环的randNo
表示一个随机行号(因为字符串将包含随机数据)。但这与问题无关
'open the word file
Set objWord = CreateObject("Word.Application")
objWord.Documents.Open strPath & fileOpen, ReadOnly:=False
objWord.Visible = True
For Each ws In Worksheets
lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
'check if enough rows
If lRow < 11 Then
myLimit = (lRow - 1)
Else
myLimit = 10
End If
'cycle through and concatenate string
For i = 1 To myLimit
randNo = Int((lRow - 2 + 1) * Rnd + 2)
dateStr = ws.Range("A" & randNo).Text
timeStr = ws.Range("B" & randNo).Text
conditionString = conditionString & vbNewLine & dateStr & " " & timeStr & " " & GetAllConditions(dateStr, timeStr)
Next i
'activate word - ready for search and replace
objWord.Activate
textToFind = "RS" & myCntr
finalStr = textToFind & conditionString
With objWord.ActiveDocument.Content.Find
.Text = textToFind
.Replacement.Text = finalStr
Debug.Print finalStr
.Execute Replace:=wdReplaceAll
End With
ThisWorkbook.Activate
myCntr = myCntr + 1
conditionString = ""
Next ws
同样,它会找到textToFind
变量fine,但只是将其替换为一个空字符串,而不是所需的(上面的)字符串
我不确定这是什么原因,也不知道我遗漏了什么或不理解什么(因为我在这里必须是一个哑巴!),所以任何帮助都将不胜感激
谢谢查找和替换的字符限制为255,您可以使用剪贴板在替换功能中绕过它。这仅适用于替换文本。“^c”控件在“查找文本”函数中不起作用
将以下内容添加到代码中:
Dim DataObj As New MSForms.DataObject
'Put string variable content on the clipboard
DataObj.SetText finalStr
DataObj.PutInClipboard
With objWord.ActiveDocument.Content.Find
.Text = textToFind
.Replacement.Text = "^c"
.Execute Replace:=wdReplaceAll
End With
'clear the clipboard
DataObj.SetText " "
DataObj.PutInClipboard
一个AIK字在查找替换方法中有256个字符的限制。您的字符串长度约为461个字符,在将其截断为255个字符后,它就可以工作了。请参考和。这太好了,谢谢@Rich Michaels。成功地实现了这一点,节省了大量的精力。
Dim DataObj As New MSForms.DataObject
'Put string variable content on the clipboard
DataObj.SetText finalStr
DataObj.PutInClipboard
With objWord.ActiveDocument.Content.Find
.Text = textToFind
.Replacement.Text = "^c"
.Execute Replace:=wdReplaceAll
End With
'clear the clipboard
DataObj.SetText " "
DataObj.PutInClipboard