我是VBA和我的新手,并致力于通过查找关键字并替换它们来将数据从Excel复制到Word的代码。我的问题是代码创建了我要复制的文档的新版本,但后来忽略了我的代码来查找和替换。我认为我的问题是我的声明,但我真的不知道。这是我的代码:
Sub CopyDatatoWord()
Dim wb As Workbook
Dim ws As Worksheet
Dim wdDoc As Word.Documents
Dim wdApp As Word.Application
Dim myrange As Range
Set wb = Workbooks("Create Health Fair Forms.xlsm")
Set ws = wb.Worksheets("Data")
Set wdApp = CreateObject("Word.Application")
Set sel = wdApp.Selection
MkDir ("" & ws.Range("FilePath").Value & "")
wdApp.DisplayAlerts = wdAlertsNone
wdApp.Documents.Open("\\hfd\repository\Screenings and Health Fair Forms\Basic Health Fair Templates\013 - CW - Template.docm", Visible = True, ReadOnly = False).SaveAs ("" & ws.Range("FilePath").Value & "\CW.docm")
wdApp.DisplayAlerts = wdAlertsAll
wdApp.Visible = True
'Code works fine until this point, and then seems to ignore everything past this point.
For i = 13 To 30
With wdApp.Selection.Find
.Text = "&Excel.Application.ws.Cells(i, 40).Value&"
.Forward = True
.Wrap = wdFindContinue
.MatchWholeWord = True
.Format = False
.Replacement.Text = "&Excel.Application.ws.Cells(i, 39).Value&"
.Execute
End With
Next i
End Sub
我在网上看过其他帖子,人们已经成功创建了像我这样的代码,我一直试图重新创建代码,但到目前为止都失败了。
非常感谢任何帮助。
答案 0 :(得分:0)
非常臭的代码
.Text = "&Excel.Application.ws.Cells(i, 40).Value&"
.Replacement.Text = "&Excel.Application.ws.Cells(i, 39).Value&"
它可能应该是
.Text = ws.Cells(i, 40).Value
.Replacement.Text = ws.Cells(i, 39).Value
此外,当我录制一个宏来查找repalce时,它会给出以下代码 标有'<<<<<<<<<<<需要调整并添加到您的代码
Selection.Find.ClearFormatting '<<<<<<<<
Selection.Find.Replacement.ClearFormatting '<<<<<<<<
With Selection.Find
.Text = "d"
.Replacement.Text = "XXXX"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False '<<<<<<<<
.MatchSoundsLike = False '<<<<<<<<
.MatchAllWordForms = False '<<<<<<<<
End With
Selection.Find.Execute Replace:=wdReplaceAll '<<<<<<<<