sharepoint - 当 Word Doc 位于服务器上时,如何从 Excel VBA 更改 Word Doc 中的文本?

标签 sharepoint excel replace ms-word vba

我有一个宏,可以根据 word 模板创建实验报告,然后将其保存到远程服务器。在我的 Excel 工作表中选择了一个单元格,运行宏,打开一个带有空白模板的 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

我知道我的代码不是最优雅的,但这对我来说并不担心,除非它影响了我想要实现的功能。任何帮助将不胜感激。这已经让我头疼了两个星期了!

最佳答案

你能帮我试试这个代码吗?

Dim oWord As Object
Dim oSelection As Object
Dim sel As Object

Set oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Activate

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.Documents(1).Content

oSelection.Select

Set sel = oWord.Selection

With sel
    .Find.ClearFormatting
    .Find.Replacement.ClearFormatting
    With .Find
        .Text = "Experiment Name"
        .Replacement.Text = Name 'Hope you have declared it somewhere?
        .Forward = True
        .Wrap = 1 'wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        sel.Find.Execute Replace:=2  'wdReplaceAll
   End With
End With

关于sharepoint - 当 Word Doc 位于服务器上时,如何从 Excel VBA 更改 Word Doc 中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017182/

相关文章:

azure - OneDrive 上传的 MS Graph API 权限

.net - 将 EventReceiver 附加到共享点站点的所有列表

visual-studio - 预部署后 SharePoint 无法识别某些术语

excel - 如何在 Excel 中显示命名范围内的名称?

R,gsub(),在给定某些条件下将 "."替换为 ","

javascript - 使用 Javascript 或 JQuery 删除特定字符后的文本

web-services - 使用 Web 服务更新自定义共享点列表中的列

python - 获取单元格的行和列,xlwings UDF在哪里被调用?

excel - 在多个工作表上添加注释 vba Excel

regex - 在 PowerShell 中查找和替换字符串的问题