[英]Find and replace or copy and paste from excel to word
我正在尝试生成一些从 excel 到 word 的数据文件 docx。 我只是在学习 VBA 的基础知识,所以我花了几个小时才发现这是一个符合逻辑的查找和替换。 但当时我尝试了很多文本,超过 255 个字符,但效果不佳。
也许您可以找到一些简单的解决方案。 这是下面的代码:
Sub gera_plano()
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set arqPlanos = objWord.Documents.Open(ThisWorkbook.Path & "\Modelo de Plano de Aula
(macro).docx")
Set conteudoDoc = arqPlanos.Application.Selection
For colTab = 1 To 20
conteudoDoc.Find.Text = Cells(1, colTab).Value
conteudoDoc.Find.Replacement.Text = Cells(2, colTab).Value
conteudoDoc.Find.Execute Replace:=wdReplaceAll
Next
arqPlanos.SaveAs2 (ThisWorkbook.Path & "\Planos\Aula - " & Cells(2, 3).Value & " -T" & Cells(2,
1).Value & ".docx")
arqPlanos.Close
objWord.Quit
Set arqPlanos = Nothing
Set conteudoDoc = Nothing
Set objWord = Nothing
MsgBox ("Plano gerado com sucesso!")
End Sub
非常感谢你的帮助
修改后,您的宏将如下所示:
Sub gera_plano()
' Note: The following code requires a reference to the
' MS Forms 2.0 Object Library, set in the VBE via Tools|References
' typically found in: C:\Windows\System32; or
' C:\Program Files (x86)\Microsoft Office\root\vfs\SystemX86
Dim objWord As Object, arqPlanos As Object, MyData As DataObject, strFnd As String
Set objWord = CreateObject("Word.Application")
Set MyData = New DataObject
Set arqPlanos = objWord.Documents.Open(ThisWorkbook.Path & "\Modelo de Plano de Aula(macro).docx")
With arqPlanos
For colTab = 1 To 20
strFnd = Cells(1, colTab).Text
MyData.SetText Cells(2, colTab).Text
MyData.PutInClipboard
With .Find
.MatchWildcards = True
.Text = strFnd
.Replacement.Text = "^c"
.Execute Replace:=wdReplaceAll
End With
Next
.SaveAs2 (ThisWorkbook.Path & "\Planos\Aula - " & Cells(2, 3).Value & " -T" & Cells(2, 1).Value & ".docx")
.Close
End With
objWord.Quit
Set arqPlanos = Nothing: Set objWord = Nothing
MsgBox ("Plano gerado com sucesso!")
End Sub
您仍然需要完成将较长的字符串转换为通配符格式的工作。 下面的链接解释了如何使用通配符:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.