简体   繁体   中英

VBA Replace From Excel to Word

I am using VBA codeI picked up online to essentially input a couple of sections and have Excel then edit a Word template, replacing <oaccount> for the inputted account number and <date> for the date of something, etc.

The issue I am facing is that when using it, the core value of the cell is being inputted and not what you see... For example, I have everything working except the date and the $ amount because when it replaces <date> and <amount> they show up as "240419" and "3450" when inputting 24/04/2019 and $3,460.00 respectively.

I want to find out how to get Excel to replace the key words with the actual displayed value of Excel.

Below is what I am using to do this:

Option Explicit

Public Sub WordFindAndReplace()
Dim ws As Worksheet, msWord As Object

Set ws = ActiveSheet
Set msWord = CreateObject("Word.Application")

With msWord
    .Visible = True
    .Documents.Open "F:\Test folder\TestFolder\Test.docx"
    .Activate

    With .ActiveDocument.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting

        .Text = "CName"
        .Replacement.Text = ws.Range("C1525").Value2

        .Forward = True
        .Wrap = 1               'wdFindContinue (WdFindWrap Enumeration)
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False

        .Execute Replace:=2     'wdReplaceAll (WdReplace Enumeration)
    End With
    .Quit SaveChanges:=True
End With
End Sub

Have you tried using the Format function on the replacement line? There's a page with a description of it here . You can also try converting it to a string in that same line using the CStr() function.

It would look something like this if you use format: .Replacement.Text = Format(ws.Range("C1525").Value2,"dd/mm/yyyy")

If you use the string conversion it would look like this: .Replacement.Text = CStr(ws.Range("C1525").Value2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM