东莞长安网站建设/百度pc端入口
我有一个基于单词模板创建实验报告的宏,然后将其保存到远程服务器。在我的Excel工作表中选中一个单元格,运行宏,使用空白模板打开Word实例,并根据所选单元格和其他数据保存该文件。我想要做的是编辑空白模板中的标题并将其更新为位于所选单元格的第一列中的实验名称。如何在Word文档位于服务器上时从Excel VBA中更改Word文档中的文本?
下面的代码在我从本地文件打开文件时工作,但当文件位于服务器上时不起作用。
Dim oWord As Object
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Activate
' Open a new instance of the ExperimentTemplate and save it
oWord.Documents.Add Template:="ExperimentTemplate", NewTemplate:=False, DocumentType:=0
oWord.ActiveDocument.SaveAs FileName:=fPath & "example.docx", FileFormat:=wdFormatXMLDocument 'fPath is the path to the folder where file will be saved on the server
oWord.ActiveDocument.Close
' Re-open file and change Experiment Name
oWord.Documents.Open FileName:=fPath & "example.docx"
Set oSelection = oWord.Selection
oSelection.Find.Text = "Experiment Name"
oSelection.Find.Replacement.Text = name 'defined as the text in the first cell of the selected column
oSelection.Find.Execute Replace:=wdReplaceAll
oWord.ActiveDocument.Save
oWord.Quit
Set oWord = Nothing
我知道,我的代码是不是最优雅,但就是喜中有忧给我的,除非它影响我想实现的功能。任何帮助将不胜感激。这已经让我头晕了两周了!
+0
你是什么意思不起作用?任何错误消息? –
+0
当我在本地运行时,位于文件顶部的文本“实验名称”被替换为位于所选单元格的第一列中的文本。但是,当我在服务器上创建的文件运行时,它似乎跳过文本替换,并且“实验名称”保留在文件的顶部。文件内没有更改 –
+1
您是否尝试通过逐步调试代码来调试代码? –