how do we open a word file using vb script - vbscript

could anyone plz tell me how to open word files using vbs windows scripting.
I tried out these two set of vbs, but windows script Host error ("The system cannot find the file specified", errorcode: 80070002) is getting displayed eventhough the file exists at the specified location.
the first vbs i tried out:
Dim sAppPath
Dim sPrgFolder
sPrgFolder=CreateObject("WScript.Shell").ExpandEnvironmentStrings("%ProgramFiles%")
sAppPath =sPrgFolder + "c:\UserGuide.doc"
WScript.CreateObject("WScript.Shell").Run sAppPath)
second vbs i tried:
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"

LittleBobbyTables explained in his comment why your first example doesn't work.
As for your second example, it doesn't work because you don't insert any spaces between the winword.exe path and the file path, so your command line looks like this:
"C:\Program Files\Microsoft Office\Office\winword.exe""C:\UserGuide.doc"
Anyway, hard-coding the winword.exe path like this is unreliable, as this path is different in 64-bit and some localized Windows versions as well as for some MS Office versions. I suggest that you use Word automation objects instead:
Set oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Documents.Open "C:\UserGuide.doc"

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"
try this revised code, check the modifications in last line :)

Thanks buddies.....
i got it working with these 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

How about this?:
set WshShell = Wscript.createObject("WScript.Shell")
WshShell.Run "Word"
WScript.Sleep 10
WshShell.AppActivate "Word"

Related

Use VBS to run a program with parameters

I'm a total vbs novice trying to perform the supposedly simple task of using a vbscript to run a single program (with parameters).
The path the to program is:
C:\Program Files (x86)\SpeedyFox\speedyfox.exe
and the parameter switch that must go with it is:
/Firefox:C:\Program Files\Firefox\Data\profile
If I wrap both sections in quotes (due to the spaces in their paths) it gives the following combined single command:
"C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile"
If I then paste this into Start > Run it works exactly as I want.
I'm just trying to achieve the same thing from a vbs script instead of manually pasting into the Run box.
I do not want the command to run within a CMD console (as other questions on here have asked). All I am trying to do is to get "C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile" to work with the shell.ShellExecute line of the script below.
Set objShell = Wscript.CreateObject ("Wscript.shell")
set shell=CreateObject("Shell.Application")
shell.ShellExecute ** WHAT DO I PUT HERE? **
set shell=nothing
but try as I might, I just keep getting WSH "Expected end of statement" error messages.
1.First : I recommend you Make it a habit to use this quote function
to make it easy for you to quote variables in these situations !
2. Second : You should use MsgBox or Wscript.echo in order to show
and debug your variables easily !
Wscript.echo DblQuote("Hello World !")
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
So, I downloaded this application (speedyfox.exe) and i tested it on my Windows 10 (32bits)
So, here is what i tested and it works like a charm on my side :
Option Explicit
Dim objShell,MyCommand,strProgramFiles,SpeedyFoxfile,Title
Title = "Execute SpeedyFox in Commandline"
Set objShell = CreateObject("Shell.Application")
strProgramFiles = GetProgramFilesPath()
SpeedyFoxfile = strProgramFiles & "\SpeedyFox\speedyfox.exe"
MsgBox "Without Double Quotes" & vbCrlf & SpeedyFoxfile,vbInformation,Title
MsgBox "With Double Quotes" & vbCrlf & DblQuote(SpeedyFoxfile),vbInformation,Title
MyCommand = "CD /D "& DblQuote(strProgramFiles &"\SpeedyFox\") &"&"& DblQuote(SpeedyFoxfile) & " " & DblQuote("/Firefox:default") & " " & DblQuote("/Chrome:Default")
MsgBox MyCommand,vbInformation,Title
Call Execute(MyCommand)
'-----------------------------------------
Function Execute(StrCmd)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
MyCmd = "CMD /K " & StrCmd & ""'
Result = ws.run(MyCmd,1,True)
Execute = Result
End Function
'-----------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'-----------------------------------------
Function GetProgramFilesPath()
Dim ws,OsType,strProgramFiles
Set ws = createObject("WScript.Shell")
OsType = ws.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE")
If OsType = "x86" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES%")
elseif OsType = "AMD64" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES(x86)%")
end if
GetProgramFilesPath = strProgramFiles
End Function
'-----------------------------------------
Sigh, reminds me of my vbscript days, now I use Ruby and it's just as simple as
´my_shell_command params´
However, back to your question: the shortest way to use ShellExecute is
CreateObject("Shell.Application").ShellExecute "application", "parameters", "dir", "verb", window
See this documentation for explanation of the parameters.
EDIT:
You have to pay attention at the quotes, they need to be passed to the shell also by using two quotes
eg CreateObject("Shell.Application").ShellExecute "C:\Program Files (x86)\SpeedyFox\speedyfox.exe", """/Waterfox:C:\Program Files\Waterfox\Data\profile"""

Writing a VBS via another VBS

I'm trying to create a VBS via another VBS, but cant handle the quotation marks, and would love to know if it's even possible.
That's the 1 line I need in my new VBS:
CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False
Main VBS code that doesn't work:
Dim oFSO, vbFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set vbFile = oFSO.CreateTextFile("try.vbs", True)
vbFile.WriteLine ""CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False""
vbFile.Close
Thanks to Sorceri, I managed to make it work by writing the following code:
Dim oFSO, vbFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set vbFile = oFSO.CreateTextFile("try.vbs", True)
vbFile.WriteLine "CreateObject(" & Chr(34) & "Wscript.Shell" & Chr(34) & ").Run """""""" & WScript.Arguments(0) & """""""", 0, False"
vbFile.Close
This is what you need to do.
Copy and paste this code
do
msgbox("haha you cant close this")
CreateObject ("WScript.Shell").Run(".\Duplicate.vbs")
loop

Shortcut target path via VBScript [duplicate]

This question already has an answer here:
How to create shortcuts having two target
(1 answer)
Closed 4 years ago.
I am trying correct a shortcut target path for MS Access using a registry key and the file location on a network share.
App Path of MS Access via Registry:
C:\Program Files\Microsoft Office 15\Root\Office 15\MSACCESS.EXE
Network location of Database:
\\H00t0000vfsrv03\Share\Folder\Database.MDB
I can not get shortcut path to take, gives me
Invalid procedure call or argument, 800A0005.
Code:
Set WSHShell = CreateObject("WScript.Shell")
ServerPath = Chr(32) & "\\H00t0000vfsrv03\Share\Folder\Database.MDB"
If Not WSHShell Is Nothing Then
DesktopPath = WSHShell.SpecialFolders("Desktop")
InstallRoot = Chr(34) & WSHShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\MSACCESS.EXE\") & Chr(34)
TargetName = InstallRoot & ServerPath
WScript.Echo TargetName
CommandName = TargetName
wscript.echo CommandName
Set MyShortcut = WSHShell.CreateShortCut(DesktopPath & "\Shorcut" & ".lnk")
MyShortcut.TargetPath = TargetName
WScript.Echo MyShortcut.TargetPath
MyShortcut.WindowStyle = 1
MyShortcut.Arguments = ""
MyShortcut.Save
Set MyShortcut = Nothing
End If
I have added
shortcut.Targetpath = """C:\Program Files\Microsoft Office 15\Root\Office 15\MSACCESS.EXE"" H00t0000vfsrv03\Share\Folder\Database.MDB"
and this last line does not work. The App Path can vary depending on the MS Access Office version. Trying to get the correct number of double quotes so that the shortcut can be mapped.
Although the .MDB extension is probably associated to MsAccess, I understand you want a shortcut to explicitely use the installed MsAccess.exe to avoid getting into trouble where a user has changed this to some other application.
When creating a shortcut like this, you need to fill in the correct values for the different properties.
The shortcuts TargetPath should be "C:\Program Files\Microsoft Office 15\Root\Office 15\MSACCESS.EXE"
The shortcuts Arguments should be "\\H00t0000vfsrv03\Share\Folder\Database.MDB"
As you are doing it now, you are trying to set the TargetPath to
"C:\PROGRA~2\MICROS~1\Office15\MSACCESS.EXE" \\H00t0000vfsrv03\Share\Folder\Database.MDB
Try this
Option Explicit
Dim WSHShell
Set WSHShell = CreateObject("WScript.Shell")
If Not WSHShell Is Nothing Then
Dim ServerPath, DesktopPath, InstallRoot, MyShortcut
ServerPath = Chr(34) & "\\H00t0000vfsrv03\Share\Folder\Database.MDB" & Chr(34)
DesktopPath = WSHShell.SpecialFolders("Desktop")
'get the long path for MSACCESS.EXE
InstallRoot = WSHShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\MSACCESS.EXE\Path")
'there SHOULD be a backslash at the end, but check anyway
If Right(InstallRoot, 1) <> "\" Then InstallRoot = InstallRoot & "\"
'add "MSACCESS.EXE" to this path and surround with double quotes
InstallRoot = Chr(34) & InstallRoot & "MSACCESS.EXE" & Chr(34)
'create the shortcut on the desktop
Set MyShortcut = WSHShell.CreateShortCut(DesktopPath & "\ShorcutToDatabase" & ".lnk")
MyShortcut.TargetPath = InstallRoot
MyShortcut.WindowStyle = 1
MyShortcut.Arguments = ServerPath
MyShortcut.Save
Set MyShortcut = Nothing
Set WSHShell = Nothing
End if

Get a VBS file to scan computer for a file

This is my first post, but I have been programming for a long time now
I just want to ask a quick question and the title explains it all. I want my VBS to run a file, but I dont want it to search just for a specific directory, I want it to just find the file if you know what I mean, because if I gave the script to anyone else, this file could be ANYWHERE on their computer.
This is the current couple of important lines that I am using for running files:
set wshshell = wscript.CreateObject("wscript.shell")
and
wshshell.run <program directory here>
You need a recursive function like this one searching for shortcuts.
Sub GenerateHotkeyInFolder(Fldr)
on error resume next
set WshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set FldrItems=Fldr.Items
For Each oFile in FldrItems
With oFile
If .IsFileSystem = true And .IsLink = true And .Type <> "Shortcut to MS-DOS Program" then
set lnk = WshShell.CreateShortcut(oFile.Path)
If lnk.hotkey <> "" then
Set fsop = fso.GetFile(.Path)
LnkName = "<b>" & fso.GetBaseName(fso.GetFile(.Path)) & "</b><br>" & fsop.ParentFolder.path & "\" & fso.GetBaseName(fso.GetFile(.Path)) & "." & fso.GetExtensionName(fso.GetFile(.Path))
TableVar = TableVar & "<tr><td><b>" & lnk.hotkey & "</b></td><td><a class=TblURL onmouseover='MakeRed()' onmouseout='MakeBlack()' onclick='FindShortcut(" & Chr(34) & lnk.fullname & Chr(34) & ")'>" & lnkname & "</a>" & "</td><td><a class=TblURL onmouseover='MakeRed()' onmouseout='MakeBlack()' onclick='FindShortcut(" & Chr(34) & lnk.targetpath & Chr(34) & ")'>" & lnk.targetpath & "</a></td></tr>" & vbcrlf
End If
ElseIf .IsFileSystem = true And .IsFolder = true then
GenerateHotkeyInFolder(.GetFolder)
End If
End With
Next
End Sub

Creating a Zip then copying folders to it

I'm trying to create a zip file, then copy three folders into it. I get the error on line 33 char 1, error state object required, I have searched and googled but just can't seem to either understand what I'm reading or understand what I really need to search for. Anyhow, here is my code.
Option Explicit
Dim objFSO, objFolder1, objFolder2, objFolder3, FolderToZip, ziptoFile, FolderGroup
Dim ShellApp, eFile, oNewZip, strZipHeader
Dim ZipName, Folder, i, Zip, Item
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder1 = objFSO.GetFolder("C:\Windows\Temp\SMSTSLog")
Set objFolder2 = objFSO.GetFolder ("C:\Windows\System32\CCM\Logs")
Set objFolder3 = objFSO.GetFolder ("C:\Windows\SysWOW64\CCM\Logs")
'For Each efile In objFolder.Files
' If DateDiff("d",eFile.DateLastModified,Now) >= 2 Then
' objFSO.MoveFile eFile, "C:\Documents and Settings\User\Desktop\Test2\"
' End If
'Next
Wscript.Sleep 2000
Set oNewZip = objFSO.OpenTextFile("C:\win7tools\testing script.zip", 8, True)
strZipHeader = "PK" & Chr(5) & Chr(6)
For i = 0 To 17
strZipHeader = strZipHeader & Chr(0)
Next
oNewZip.Write strZipHeader
oNewZip.Close
Set oNewZip = Nothing
WScript.Sleep 5000
FolderGroup = Array(objFolder1,objFolder2,objFolder3)
FolderToZip = "FolderGroup"
ZipToFile = "C:\Win7tools\Test Script.zip"
Set ShellApp = CreateObject("Shell.Application")
Set Zip = ShellApp.NameSpace(ZipToFile)
'Set Folder = ShellApp.NameSpace(FolderToZip)
ShellApp.NameSpace(FolderGroup).CopyHere Zip.NameSpace(ZipToFile)
WScript.Sleep 10000
set ShellApp = Nothing
set FolderToZip = Nothing
set ZipToFile = Nothing
When in doubt, read the documentation:
retVal = Shell.NameSpace(
vDir
)
Parameters
vDir [in]
Type: Variant
The folder for which to create the Folder object. This can be a string that specifies the path of the folder or one of the ShellSpecialFolderConstants values. Note that the constant names found in ShellSpecialFolderConstants are available in Visual Basic, but not in VBScript or JScript. In those cases, the numeric values must be used in their place.
The NameSpace method expects either a string with a path or the integer value of one of the ShellSpecialFolderConstants, not an array of Folder objects. Also you got the order wrong. The object on which you call the copyHere method is the zip file. The argument is what you want to copy to the zip file (a path string should do just fine here). Plus, the name of the zip file you create is different from the name of the zip file you try to add the folders to.
Change your code to this:
folder1 = "C:\Windows\Temp\SMSTSLog"
folder2 = "C:\Windows\System32\CCM\Logs"
folder3 = "C:\Windows\SysWOW64\CCM\Logs"
zipfile = "C:\Win7tools\Test Script.zip"
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.OpenTextFile(zipfile, 2, True).Write "PK" & Chr(5) & Chr(6) _
& String(18, Chr(0))
Set ShellApp = CreateObject("Shell.Application")
Set zip = ShellApp.NameSpace(zipfile)
zip.CopyHere folder1
zip.CopyHere folder2
zip.CopyHere folder3
WScript.Sleep 10000
WinZip has a Command Line Interface. You might have to download and install it depending on your version: http://www.winzip.com/prodpagecl.htm
The below is a test script that works for WinZip version 9.0 if it helps.
Const WinZip = "C:\Program Files\WinZip9.0\wzzip.exe" 'WinZip Version 9.0
BasePath = "C:\Path\To\Folders\"
strZipFilePath = BasePath & "Test.zip"
strArchiveMe = BasePath & "Folder_A"
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(WinZip) Then
MsgBox "WinZip (wzzip.exe) Does Not Exist"
WScript.Quit
End If
'''// For Below Command - Change "-a" TO "-mu" To Auto Delete The file After Zip Is Created
'''// For Below Command - Change "-yb" TO "-ybc" To Answer YES To all Promps and not Terminate Operation
strcommand = Chr(34) & WinZip & Chr(34) & " -a -yb " & Chr(34) & strZipFilePath & Chr(34) & " " & Chr(34) & strArchiveMe & Chr(34)
objShell.Run strcommand, 1, True
The command format is:
winzip [action] [options] [Zip Path] [Path to file/folder to zip]

Resources