将多行字符串从Excel传递到Word

问题描述 投票:0回答:1

我目前正在尝试将多行字符串从Excel传递到Word文档。我首先使用单元格数据创建字符串,然后尝试通过搜索和替换方法将其传递给Word。代码是在Word中找到单词(在哪里替换),但它用空字符串替换它。这有几件事;首先,我在替换发生时Debug.Print字符串,并且在即时窗口中字符串已满。其次,当我用一个简单的字符串替换这个单词时,它可以很好地替换它,这使我相信我试图首先发送到Word的多行字符串似乎存在问题。以下是我的代码以及其他可能相关的内容。

下面是循环遍历每个工作表的For Each循环,并根据该工作表创建相关的字符串。 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

下面是从VBE中的立即窗口打印出的finalStr示例:

RS7
25/09/2018 08:00:00 C2, C5, C6, C7, C8, C9, C10, 
06/08/2018 08:00:00 C4, C6, C7, 
25/01/2019 14:30:00 C1, C2, C5, C6, C7, C8, C11, 
05/11/2018 08:00:00 C6, C7, 
31/12/2018 20:30:00 C1, C2, C6, C7, C8, C10, C11, 
30/11/2018 08:00:00 C2, C6, C7, C8, 
25/09/2018 08:00:00 C2, C5, C6, C7, C8, C9, C10, 
11/02/2019 14:30:00 C1, C4, C6, C7, C8, 
01/10/2018 14:30:00 C1, C2, C5, C6, C7, C8, C9, C11, 
11/09/2018 14:30:00 C1, C2, C3, C4, C6, C7, C8, C9, C10, C11, 

同样,它发现textToFind变量很好,但只是用空字符串而不是所需的(上面)字符串替换它。

我不确定这个原因,或者我缺少什么或不理解(因为我必须在这里做个假人!)所以任何帮助将不胜感激!

谢谢

excel vba ms-word word-vba
1个回答
1
投票

查找和替换的字符限制为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
© www.soinside.com 2019 - 2024. All rights reserved.