【问题标题】:how do we open a word file using vb script我们如何使用vb脚本打开一个word文件
【发布时间】:2022-05-22 21:14:23
【问题描述】:

谁能告诉我如何使用 vbs windows 脚本打开 word 文件。

我尝试了这两组vbs,但是即使文件存在于指定位置,也会显示windows script Host error ("The system cannot find the file specified", errorcode: 80070002)。

我尝试的第一个 vbs:

Dim sAppPath
Dim sPrgFolder
sPrgFolder=CreateObject("WScript.Shell").ExpandEnvironmentStrings("%ProgramFiles%") 
sAppPath =sPrgFolder + "c:\UserGuide.doc"
WScript.CreateObject("WScript.Shell").Run sAppPath)

我尝试的第二个 vbs:

OPTION EXPLICIT
dim fso, ws, file_to_open, OFFICE_PATH
Set ws = WScript.CreateObject("WScript.Shell")
OFFICE_PATH = "C:\Program Files\Microsoft Office\Office"
file_to_open = CHR(34) & "C:\UserGuide.doc" & CHR(34)
ws.Run CHR(34)& OFFICE_PATH & "\winword.exe" & CHR(34) & file_to_open, 0, "FALSE"

【问题讨论】:

  • 您的第一个代码不起作用,因为您在sPrgFolder 中获得了程序文件夹路径,其中可能包含类似于C:\Program Files\Microsoft Office\OFFICE11 的内容。然后添加C:\UserGuide.doc` to the variable, so you'll end up with: C:\Program Files\Microsoft Office\OFFICE11\C:\UserGuide.doc`,这根本行不通。不过,我已经没时间看第二个 vbs 了。

标签: vbscript ms-word office-interop


【解决方案1】:

LittleBobbyTables 在他的评论中解释了为什么您的第一个示例不起作用。

至于你的第二个例子,它不起作用,因为你没有在 winword.exe 路径和文件路径之间插入任何空格,所以你的命令行看起来像这样:

"C:\Program Files\Microsoft Office\Office\winword.exe""C:\UserGuide.doc"


无论如何,像这样硬编码 winword.exe 路径是不可靠的,因为该路径在 64 位和一些本地化的 Windows 版本以及一些 MS Office 版本中是不同的。我建议您改用 Word 自动化对象:

Set oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Documents.Open "C:\UserGuide.doc"

【讨论】:

    【解决方案2】:
    OPTION EXPLICIT
    dim fso, ws, file_to_open, OFFICE_PATH
    Set ws = WScript.CreateObject("WScript.Shell")
    OFFICE_PATH = "C:\Program Files\Microsoft Office\Office"
    file_to_open = CHR(34) & "C:\UserGuide.doc" & CHR(34)
    ws.Run CHR(34) & OFFICE_PATH & "\winword.exe " & CHR(34) & file_to_open, 0, "FALSE"
    

    试试这个修改后的代码,检查最后一行的修改:)

    【讨论】:

      【解决方案3】:

      谢谢各位大佬..... 我可以使用这些 vbs。

      Dim shell, quote, pgm, fname
      
      set shell = WScript.CreateObject("WScript.Shell")
      quote = Chr(34)
      pgm = "WINWORD"
      fname = "C:\UserGuide.doc"
      shell.Run quote & pgm & quote & " " &fname
      

      【讨论】:

        【解决方案4】:

        这个怎么样?

        set WshShell = Wscript.createObject("WScript.Shell")
        WshShell.Run "Word"
        WScript.Sleep 10
        
        WshShell.AppActivate "Word"
        

        【讨论】:

        • 您的答案可以通过添加有关代码的作用以及它如何帮助 OP 的更多信息来改进。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        相关资源
        最近更新 更多