This question already has an answer here:
While Running the vba script i am getting error Microsoft VBScript runtime error: object required : 'DoCmd'
(1 answer)
Closed 8 years ago.
Hi Any one please help me..
while running the vba script i am getting error--object DoCmd need to create.
My script is given below..
ExecuteInsert
Sub ExecuteInsert()
Dim sheetPath
Dim dbs, DbFullName, acc
Set acc = CreateObject("Access.Application")
DbFullName = "D:\G\Diamond\FINAL MS-Access\Demo\MS-Access project.accdb"
Set dbs = acc.DBEngine.OpenDatabase(DbFullName, False, False)
dbs.Execute "Delete from TempRoadMap"
sheetPath = "C:\Users\270784\Desktop\CSPRV scheduled work - 2014 through 1-26-14.xlsx"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel97, "TempRoadMap", sheetPath, True
MsgBox "Imported Sheet1 from " & sheetPath & " Successfully!"
dbs.Execute "Delete from RoadMap"
dbs.Execute "INSERT INTO [RoadMap] ( Release_Name,SPRF,SPRF_CC,Estimate_Type,PV_Work_ID,SPRF_Name,Estimate_Name,Project_Phase,CSPRV_Status,Scheduling_Status,Impact_Type,Onshore_Staffing_Restriction,Applications,Total_Appl_Estimate,Total_CQA_Estimate,Estimate_Total,Requested_Release,Item_Type,Path) SELECT [TempRoadMap.Release Name], [TempRoadMap.SPRF], [TempRoadMap.Estimate (SPRF-CC)],[TempRoadMap.Estimate Type],[TempRoadMap.PV Work ID],[TempRoadMap.SPRF Name],[TempRoadMap.Estimate Name],[TempRoadMap.Project Phase],[TempRoadMap.CSPRV Status],[TempRoadMap.Scheduling Status],[TempRoadMap.Impact Type],[TempRoadMap.Onshore Staffing Restriction],[TempRoadMap.Applications],[TempRoadMap.Total Appl Estimate],[TempRoadMap.Total CQA Estimate],[TempRoadMap.Estimate Total],[TempRoadMap.Requested Release],[TempRoadMap.Item Type],[TempRoadMap.Path] FROM [TempRoadMap] "
dbs.Close
MsgBox "Done"
End Sub
Assuming that by "...through cmd prompt..." you mean to imply that you are running this script as part of a VBScript file, here are the changes you would want to make:
DoCmd is a child of an Access.Application, and it can only be referenced globally in the scope of an Access database. To reference it in VBScript, you must explicitly use an Access.Application instance, which you have as variable acc. Modify the beginning of the DoCmd line like so:
acc.DoCmd.TransferSpreadsheet
VBScript won't recognize Access constants like acImport or acSpreadsheetTypeExcel97, so you will have to replace them with their actual values. A quick look through msdn reveals that acImport is 0 and acSpreadsheetTypeExcel97 doesn't exist, but acSpreadsheetTypeExcel8 (Excel 97 format) is 8. So now the DoCmd line looks like:
acc.DoCmd.TransferSpreadsheet 0, 8, "TempRoadMap", sheetPath, True
VBScript does not have MsgBox - this is only available through VBA. Instead, you can use Wscript.Echo. For example, the last line would be: WScript.Echo "Done"
If you still have issues after making those changes, please let me know with a comment below.
VBScript certainly does have msgbox and echo is not part of vbscript but of Windows Scripting Host.
Related
I am working on a script with vbscript, and I would like it to terminate itself after x number of minutes.
I was thinking something like grabbing the time when the script starts and then keeping the whole thing in a loop until the time is x number of minutes after the start time, but I need it to keep checking in the background, and not just wait until a loop is complete.
I want a message or something that notifies the user they took too long, which I can do myself.
Is there any way to keep track of the time in the background, or will it be a bit of a drawn-out process to determine it?
Re-launching the script with //T:xx as suggested by Ekkehard.Horner is probably your best option. Another, slightly different, approach could look like this:
Const Timeout = 4 'minutes
timedOut = False
If WScript.Arguments.Named.Exists("relaunch") Then
'your code here
Else
limit = DateAdd("n", Timeout, Now)
cmd = "wscript.exe """ & WScript.ScriptFullName & """ /relaunch"
Set p = CreateObject("WScript.Shell").Exec(cmd)
Do While p.Status = 0
If Now < limit Then
WScript.Sleep 100
Else
On Error Resume Next 'to ignore "invalid window handle" errors
p.Terminate
On Error Goto 0
timedOut = True
End If
Loop
End If
If timedOut Then WScript.Echo "Script timed out."
You'd still be re-launching the script, but in this case it's your script killing the child process, not the script interpreter.
Here is another short and elegant solution which allows to terminate both the script and the external executable ran asynchronously, via WScript.Timeout
Option Explicit
Dim oSmallWrapperWshExec
WScript.Timeout = 7
Set oSmallWrapperWshExec = New cSmallWrapperWshExec
' Some code here
MsgBox "Waiting timeout" & vbCrLf & vbCrLf & "You may close notepad manually and/or press OK to finish script immediately"
Class cSmallWrapperWshExec
Private oWshShell
Private oWshExec
Private Sub Class_Initialize()
Set oWshShell = CreateObject("WSCript.Shell")
With oWshShell
Set oWshExec = .Exec("notepad")
.PopUp "Launched executable", 2, , 64
End With
End Sub
Private Sub Class_Terminate()
On Error Resume Next
With oWshShell
If oWshExec.Status <> 0 Then
.PopUp "Executable has been already terminated", 2, , 64
Else
oWshExec.Terminate
.PopUp "Terminated executable", 2, , 64
End If
End With
End Sub
End Class
I appreciate all of the answers here, but they are more complicated than I wanted to get in to.
I was very surprised to find out that there is a way to do it built into WScript.
WScript.Timeout = x_seconds
cscript
Usage: CScript scriptname.extension [option...] [arguments...]
Options:
//B Batch mode: Suppresses script errors and prompts from displaying
//D Enable Active Debugging
//E:engine Use engine for executing script
//H:CScript Changes the default script host to CScript.exe
//H:WScript Changes the default script host to WScript.exe (default)
//I Interactive mode (default, opposite of //B)
//Job:xxxx Execute a WSF job
//Logo Display logo (default)
//Nologo Prevent logo display: No banner will be shown at execution time
//S Save current command line options for this user
**//T:nn Time out in seconds: Maximum time a script is permitted to run**
//X Execute script in debugger
//U Use Unicode for redirected I/O from the console
Update:
To help people who downvote a plain (and to the point) citation of cscript.exe's usage message (how can that be wrong?) to see the light through #PanayotKarabakalov's smoke screen:
The claim:
using //T switch not guarantee real time accuracy
that all 5 Echo command executed, even if the Sleep time between them
is 1.5 second and the //T is set to 4
The evidence:
The script is restarted via:
CreateObject("WScript.Shell").Run "WScript " & _
Chr(34) & WScript.ScriptFullName & _
Chr(34) & " /T:4", 0, False
which does not contain the host-specific //T (as opposed to the script-specific /T) switch.
The (counter) argument:
Whatever way you start the first instance of the script (//T or no //T), the second/relaunched instance will never have a time out and will always run to the bitter end.
If you still have doubts, change the invocation in P.'s script to
CreateObject("WScript.Shell").Run "WScript //T:4 " & _
and try it out.
I have an command line app that queries some Scheduled Tasks and returns 0 if ready and 1 if not.
I need to get that return code from a VBScript, but I am getting 0 always, even if the app returns 1. This is the code I have:
StrCommandLine = """C:\Program Files (x86)\App\TaskValidator\TaskValidator.exe"""
Set oshell = CreateObject("WScript.Shell")
iReturn = oShell.run(StrCommandLine,0,true)
wscript.echo iReturn
If I run the app from a CMD, it returns 1 if not ready. I think it is because I am getting the last error code from CMD itself.
Any help you can give me?
From Help http://download.microsoft.com/download/winscript56/Install/5.6/W982KMeXP/EN-US/scrdoc56en.exe
You are not setting an error code.
Quit Method (Windows Script Host)
Forces script execution to stop at any time.
object.Quit([intErrorCode])
object
WScript object.
intErrorCode
Optional. Integer value returned as the process's exit code. If you do not include the intErrorCode parameter, no value is returned.
Remarks
The Quit method can return an optional error code. If the Quit method
I want to have a URL in the helpfile part of the VBScript MsgBox() function. How do I do that?
Here is the code:
Dim error
Dim helpPath
helpPath = "http://www.example.com/example-support-page"
error = MsgBox("There was an error doing whatever.", vbSystemModal + vbCritical, "Uh oh!")
helpPath = MsgBox("", vbSystemModal + vbMsgBoxHelpButton, "", helpPath)
I used this answer and it worked:
Not sure of any way to get a hyperlink into a msgbox. However, you can format your msgbox as 'Oops - shall we go to the help page?' and use Yes/No buttons then code the 'Yes' option as and open() command with the URL as the parameter to invoke the browser to open via the OS. No reason why that would not work.
- Vanquished Wombat
(I copied and pasted it because I can't seem to mark a comment as an answer.)
We recently upgraded to ALM 11 at work and I am trying to add some formatting to the run details field in the HP Run Results Viewer application. We have existing code from older versions of ALM that displays the info on multiple lines:
pass =
fail =
warning =
The code we used was like this:
Stats = "Passed = " & vbCrLf & "Failed = " & vbCrLf & "Warning = "
Reporter.ReportEvent micFail, "Test", stats
In ALM 11's viewer it shows up as pass= fail= warning= all on one line.
Is there a way to add the new line to the results? This is our most simple example and much of the results are currently unreadable.
Unfortunately, I do not have any good explanation for why your code doesn't work. It looks OK to me. However, I have an alternative approach that might do the trick: Have you tried to use ASCII and Unicode Character Codes instead of the VBScript built-in "vbCrLf"?
Using the ASCII approach, your code would look like this:
Stats = "Passed = " & Chr(10) & "Failed = " & Chr(10) & "Warning = "
Chr(10) equals an NL line feed, i.e. a new line. Chr(13) would do a carriage return, if you want to try that instead, or in addition to, the line feed.
More information on the Chr function can be found here: https://msdn.microsoft.com/en-us/library/ws6aa3sf(v=vs.84).aspx.
UPDATE:
It looks like this is a known defect in QTP 11 - see http://h30499.www3.hp.com/t5/Unified-Functional-Testing/QTP-run-result-viewer-issue-with-VBCRLF/td-p/5898077.
There is another approach you could try (unless upgrading QTP is an option), using HTML and LogEvent - see http://www.joecolantonio.com/2014/11/06/revealed-four-secret-functions-hidden-in-qtp-and-uft/, but beware of the limitations mentioned in the comments section.
call main()
sub main()
Dim scmd
Set scmd = "c:\windows\system32\cscript.exe //nologo c:\s.vbs"
createobject("wscript.shell").run scmd,0,false
end sub
It gives me error:
Object required: '[string: "c:\windows\system32\"]' Code 800A01A8
Update
As it's not clear feel it best to point out your Object Required issue is due to this line
Set scmd = "c:\windows\system32\cscript.exe //nologo c:\s.vbs"
This is because an Object is expected but you are assigning it a string, by removing the Set your code will work (As Ekkehard.Horner has pointed out).
Below is my interpretation of situation. First looking at your code it almost looked like it had mixed the instantiation of the WScript.Shell object with the command line for the .Run() method. It was my first stab at breaking down the code, rearranging it then putting it back together.
Original Answer
Your Set scmd should be instantiating the WScript.Shell (As Ekkehard.Horner points out you can use Server.CreateObject("WScript.Shell").Run for a one off reference but I wouldn't recommend it).
The .Run() should be executed by the instantiated scmd object and passed the command line to execute.
Here is an example I've renamed some of the variables (scmd to cmd for example).
Call main()
Sub main()
'Renamed variables to cmd is your object and cmdline is your file path.
Dim cmd, cmdline
'Instantiate WshShell object
Set cmd = Server.Createobject("WScript.Shell")
'Set cmdline variable to file path
cmdline = "c:\windows\system32\cscript.exe //nologo c:\s.vbs"
'Execute Run and return immediately
Call cmd.Run(cmdline, 0, False)
End Sub
Things to consider
When using WScript.Shell in Classic ASP to run executables there are some things to consider;
Run command will execute using the current Application Pool identity.
Run will execute the executable on the server not at the client (server side).
As
>> WScript.Echo CreateObject("WScript.Shell").CurrentDirectory
>>
E:\trials\SoTrials\answers\trials\AlgoTaBu\SuSo\wsf
proves, there is no rule or law at all that "Your Set scmd should be instantiating the WScript.Shell". Putting the command to execute in string variable scmd (or perhaps better sCmd) and not creating a variable for an only-once-used value are good practices.
The revised version (minus the stupid Set):
call main()
sub main()
Dim scmd
scmd = "c:\windows\system32\cscript.exe //nologo c:\s.vbs"
createobject("wscript.shell").run scmd,0,false
end sub
will work just as well as Lankymart's version.
To spell everything out:
The Set keyword, its semantic, and its error message are design flaws, that make VBScript harder to use correctly. "site:stackoverflow.com vbscript "object required" Set" results in 1500 hits. Even if much of those hits do not concern the "Set x = 'non-object' blunder, that's clearly too much. To explain/excuse those IEDs you have to consider that BASIC is a stone age language.
A person learning VBScript is entitled to be surprised by the "Set x = 'non-object' mistake twice. If it happens trice (or more often), he/she should be ashamed (and keep silent about it). Above all that problem should not pollute this site.
When I posted my contribution, all answers/comments - with the exception of Alex K.'s 'Just delete the Set' - emphasized/concentrated on the .Run statement; one answer called the script "topsy curvy", one answer even repeated the atrocity. So I tried to point out that there is exactly one error: The spurious Set.
I failed miserably. Evidence: John Saunders changed the title from "VBScript error" (unspecific but true) to "“Object required” when calling Run on Wscript.Shell" (specific but wrong), Lankymart engaged in psychological/philological research to save the Set at the expense of the string.
My only hope: Everybody reading this will be so disgusted by my harping on the Set, that she/he from now on will think twice when typing:
wtf
Set x = " ---- stop or be damned!!!
Set x = obj.getNumber() + 4 ---- oh no!!!
All to no avail - Same mistake again
I am not sure, try change
Set scmd = "c:\windows\system32\cscript.exe //nologo c:\s.vbs"
to
Set scmd = "c:\windows\system32\cscript.exe" //nologo "c:\s.vbs"