Could someone tell me why does this line error:
set my_obj = wscript.CreateObject("ObjectTest","pref_")
It gives this error:
Object required: ‘wscript’
If I run this code:
Set WScript = CreateObject("WScript.Shell")
set my_obj = CreateObject("ObjectTest","pref_")
I get this error instead:
Object doesn’t support this property or method: ‘CreateObject’
I’m running the vbscript from within a Delphi app.
Remy Lebeau
550k31 gold badges451 silver badges764 bronze badges
asked Feb 3, 2016 at 17:48
1
Object required: ‘wscript’
I’m running the vbscript from within a Delphi app.
This is why your script is failing. The wscript
object is only defined when the script is run by wscript.exe
. To do what you are attempting, you need to implement your own object and provide it to the script environment for the script code to access when needed.
Assuming you are using IActiveScript
to run your script, you can write a COM Automation object that implements the IDispatch
interface, and then you can create an instance of that object and give it to the IActiveScript.AddNamedItem()
method before then calling IActiveScript.SetScriptState()
to start running the script.
For example, write an Automation object that exposes its own CreateObject()
method, give it to AddNamedItem()
with a name of App
, and then the script can call App.CreateObject()
. Your CreateObject()
implementation can then create the real requested object and hook up event handlers to it as needed. To fire events back into the script, use the IActiveScript.GetScriptDispatch()
method to retrieve an IDispatch
for the desired procedure defined in the script, and then use IDispatch.Invoke()
with DISPID 0 and the DISPATCH_METHOD
flag to execute that procedure with the desired input parameters.
Your object can implement any properties and methods that you want the script to have access to.
answered Feb 4, 2016 at 6:19
Remy LebeauRemy Lebeau
550k31 gold badges451 silver badges764 bronze badges
The reason your script is failing is due to a few occurrences.
- DO NOT use «
WScript
» as an object especially while coding inWindows-Based Script Host
(orWSH
), as the program assumes you are runningwscript.exe
or callingWScript
commands. - Use
Dim
! If the first rule wasn’t null, this is why. Using command «Option Explicit
» in VBScript requires users toDim
anyobject
or calling of anobject
.
A fixed code would be:
Option Explicit
Dim 1, 2
Set 1 = WScript.CreateObject("WScript.Shell")
Set 2 = WScript.CreateObject("ObjectTest", "pref_")
answered Feb 23, 2021 at 3:05
I’ve been searching for awhile, but I cannot seem to find the answer. I am making a gui based program selector and I am quite new to VBS and HTA. I’ve made a auto-typer and I cannot seem to figure out why it does not work in HTA. It works fine on its own.
<head>
<title>Gui Bases Program Selector.</title>
<HTA:APPLICATION
APPLICATIONNAME="HTA Test"
SCROLL="yes"
SINGLEINSTANCE="yes"
WINDOWSTATE="maximize"
>
</head>
<script language="VBScript">
Sub TestSub
Set shell = CreateObject("wscript.shell")
strtext = InputBox("What Do you want your message do be?")
strtimes = InputBox ("How many times would you like you type it?")
If Not IsNumeric(strtimes) Then
lol = MsgBox("Error = Please Enter A Number.")
WScript.Quit
End If
MsgBox "After you click ok the message will start in 5 seconds "
WScript.Sleep(5000)
Tor i=1 To strtimes
shell.SendKeys(strtext & "")
shell.SendKeys "{Enter}"
WScript.Sleep(75)
Next
End Sub
</script>
<body>
<input type="button" value="AutoTyper" name="run_button" onClick="TestSub"><p>
</body>
asked Nov 7, 2016 at 23:05
8
The HTA engine doesn’t provide a WScript
object, so things like WScript.Quit
or WScript.Sleep
don’t work in HTAs. To programmatically exit from an HTA use Self.Close
or window.Close
. For replacing the Sleep
method see the answers to this question.
answered Nov 8, 2016 at 10:34
Ansgar WiechersAnsgar Wiechers
192k24 gold badges247 silver badges321 bronze badges
Перейти к содержимому раздела
Серый форум
разработка скриптов
Вы не вошли. Пожалуйста, войдите или зарегистрируйтесь.
Страницы 1
Чтобы отправить ответ, вы должны войти или зарегистрироваться
1 2012-09-16 10:10:04
- gts
- Участник
- Неактивен
- Рейтинг : [0|0]
Тема: VBScript: WScript — требуется объект
конструкции типа WScript.Echo или WScript.Sleep вызывают ошибку «Требуется объект», даже в чужих работающих примерах. Какие-то компоненты не установлены или в чем может быть причина?
2 Ответ от yuriy2000 2012-09-16 11:48:01
- yuriy2000
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: VBScript: WScript — требуется объект
Скорее всего потому, что Вы примеры используете в скрипте внутри HTML.
Такие конструкции как WScript.Echo или WScript.Sleep могут быть использованы только если вы используете запуск скрипта через Wscript.exe или Cscript.exe.
3 Ответ от gts 2012-09-16 12:11:05 (изменено: gts, 2012-09-16 12:12:54)
- gts
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: VBScript: WScript — требуется объект
Спасибо за ответ. Я пытаюсь использовать вышеуказанные конструкции в hta-приложении. Подскажите пожалуйста, как «использовать запуск скрипта через Wscript.exe» на практике (для «чайников»), а если в случае hta-приложения этого сделать нельзя, то как приостановить выполнение скрипта, кроме «вечного цикла».
4 Ответ от yuriy2000 2012-09-16 12:31:57
- yuriy2000
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: VBScript: WScript — требуется объект
gts пишет:
Подскажите пожалуйста, как «использовать запуск скрипта через Wscript.exe» на практике (для «чайников»), а если в случае hta-приложения этого сделать нельзя, то как приостановить выполнение скрипта, кроме «вечного цикла».
Использовать скрипт очень просто — создайте файл с расширением .VBS и запускайте его.
Для удобства работы с большим потоком выводимых данных необходимо использовать Cscript, т.к. при запуске через WScript.exe метод WScript.Echo эквивалентен MsgBox.
Использование: CScript имя_сценария.расширение [параметры…] [аргументы…]
Параметры:
//B Пакетный режим: подавляются отображение ошибок и запросов сценария
//D Включение режима Active Debugging
//E:ядро Использование указанного ядра для выполнения сценария
//H:CScript Стандартный сервер сценариев заменяется на CScript.exe
//H:WScript Стандартный сервер сценариев заменяется на WScript.exe (по умолчанию)
//I Диалоговый режим (по умолчанию, в противоположность //B)
//Job:xxxx Выполнение указанного задания WSF
//Logo Отображать сведения о программе (по умолчанию)
//Nologo Не отображать сведения о программе во время выполнения
//S Сохранить для данного пользователя текущие параметры командной строки
//T:nn Интервал ожидания (в секундах): максимальное время выполнения сценария
//X Выполнение сценария в отладчике
//U Использование кодировки Юникод при перенаправлении ввода-вывода с консоли
5 Ответ от gts 2012-09-16 15:06:34
- gts
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: VBScript: WScript — требуется объект
Спасибо, т.е., если я вынесу часть кода во внешний vbs-файл и запущу WScript или Cscript c ним в качестве сценария из html-страницы или hta-приложения методами ShellExecute или Run, то объект Wscript.Sleep сработает?
6 Ответ от alexii 2012-09-16 15:42:20
- alexii
- Разработчик
- Неактивен
Re: VBScript: WScript — требуется объект
Сработает. Но на HTA это не отразится.
7 Ответ от gts 2012-09-16 16:21:37 (изменено: gts, 2012-09-16 16:23:24)
- gts
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: VBScript: WScript — требуется объект
Спасибо за участие, очевидно, запуск WScript.exe методами Run и ShellExecute создает отдельный процесс, на который и действует код сценария-параметра. Но есть же какой-то способ приостановить hta-приложение на время загрузки Excel, вызываемого из скрипта в hta, не загружая процессор циклом? Ведь если делать опрос наступления события, а оно не наступит? И какое время ожидания считать приемлемым в зависимости от техники? Может быть, есть какой либо-метод Shell.Application или WScript.Shell — эти объекты доступны, но я не нашла ничего подходящего. Или можно как-то воспользоваться ответами на тему «CMD/BAT: sleep штатными средствами», но чтобы это воздействовало на заданную работающую в ОС задачу, т.е. что-то на уровне ОС, а не изнутри самой задачи?
8 Ответ от Serge Yolkin 2012-09-16 17:13:05
- Serge Yolkin
- Разработчик
- Неактивен
- Рейтинг : [1|0]
Re: VBScript: WScript — требуется объект
Способа приостановить скрипт в .hta приложении, в общем-то нет. Есть трансляция WScript в hta, но лучше, по возможности, изменить алгоритм самого скрипта так, чтобы можно было использовать setTimeOut и setInterval.
9 Ответ от gts 2012-09-16 17:45:27
- gts
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: VBScript: WScript — требуется объект
Спасибо
10 Ответ от alexii 2012-09-16 17:49:44
- alexii
- Разработчик
- Неактивен
Re: VBScript: WScript — требуется объект
11 Ответ от gts 2012-09-16 18:55:00
- gts
- Участник
- Неактивен
- Рейтинг : [0|0]
Re: VBScript: WScript — требуется объект
Спасибо, буду изучать
Сообщения 11
Страницы 1
Чтобы отправить ответ, вы должны войти или зарегистрироваться
I’ve been searching for awhile, but I cannot seem to find the answer. I am making a gui based program selector and I am quite new to VBS and HTA. I’ve made a auto-typer and I cannot seem to figure out why it does not work in HTA. It works fine on its own.
<head>
<title>Gui Bases Program Selector.</title>
<HTA:APPLICATION
APPLICATIONNAME="HTA Test"
SCROLL="yes"
SINGLEINSTANCE="yes"
WINDOWSTATE="maximize"
>
</head>
<script language="VBScript">
Sub TestSub
Set shell = CreateObject("wscript.shell")
strtext = InputBox("What Do you want your message do be?")
strtimes = InputBox ("How many times would you like you type it?")
If Not IsNumeric(strtimes) Then
lol = MsgBox("Error = Please Enter A Number.")
WScript.Quit
End If
MsgBox "After you click ok the message will start in 5 seconds "
WScript.Sleep(5000)
Tor i=1 To strtimes
shell.SendKeys(strtext & "")
shell.SendKeys "{Enter}"
WScript.Sleep(75)
Next
End Sub
</script>
<body>
<input type="button" value="AutoTyper" name="run_button" onClick="TestSub"><p>
</body>
asked Nov 7, 2016 at 23:05
8
The HTA engine doesn’t provide a WScript
object, so things like WScript.Quit
or WScript.Sleep
don’t work in HTAs. To programmatically exit from an HTA use Self.Close
or window.Close
. For replacing the Sleep
method see the answers to this question.
answered Nov 8, 2016 at 10:34
Ansgar WiechersAnsgar Wiechers
189k23 gold badges240 silver badges313 bronze badges
I’ve been searching for awhile, but I cannot seem to find the answer. I am making a gui based program selector and I am quite new to VBS and HTA. I’ve made a auto-typer and I cannot seem to figure out why it does not work in HTA. It works fine on its own.
<head>
<title>Gui Bases Program Selector.</title>
<HTA:APPLICATION
APPLICATIONNAME="HTA Test"
SCROLL="yes"
SINGLEINSTANCE="yes"
WINDOWSTATE="maximize"
>
</head>
<script language="VBScript">
Sub TestSub
Set shell = CreateObject("wscript.shell")
strtext = InputBox("What Do you want your message do be?")
strtimes = InputBox ("How many times would you like you type it?")
If Not IsNumeric(strtimes) Then
lol = MsgBox("Error = Please Enter A Number.")
WScript.Quit
End If
MsgBox "After you click ok the message will start in 5 seconds "
WScript.Sleep(5000)
Tor i=1 To strtimes
shell.SendKeys(strtext & "")
shell.SendKeys "{Enter}"
WScript.Sleep(75)
Next
End Sub
</script>
<body>
<input type="button" value="AutoTyper" name="run_button" onClick="TestSub"><p>
</body>
asked Nov 7, 2016 at 23:05
8
The HTA engine doesn’t provide a WScript
object, so things like WScript.Quit
or WScript.Sleep
don’t work in HTAs. To programmatically exit from an HTA use Self.Close
or window.Close
. For replacing the Sleep
method see the answers to this question.
answered Nov 8, 2016 at 10:34
Ansgar WiechersAnsgar Wiechers
189k23 gold badges240 silver badges313 bronze badges
Could someone tell me why does this line error:
set my_obj = wscript.CreateObject("ObjectTest","pref_")
It gives this error:
Object required: ‘wscript’
If I run this code:
Set WScript = CreateObject("WScript.Shell")
set my_obj = CreateObject("ObjectTest","pref_")
I get this error instead:
Object doesn’t support this property or method: ‘CreateObject’
I’m running the vbscript from within a Delphi app.
Remy Lebeau
534k30 gold badges442 silver badges748 bronze badges
asked Feb 3, 2016 at 17:48
1
Object required: ‘wscript’
I’m running the vbscript from within a Delphi app.
This is why your script is failing. The wscript
object is only defined when the script is run by wscript.exe
. To do what you are attempting, you need to implement your own object and provide it to the script environment for the script code to access when needed.
Assuming you are using IActiveScript
to run your script, you can write a COM Automation object that implements the IDispatch
interface, and then you can create an instance of that object and give it to the IActiveScript.AddNamedItem()
method before then calling IActiveScript.SetScriptState()
to start running the script.
For example, write an Automation object that exposes its own CreateObject()
method, give it to AddNamedItem()
with a name of App
, and then the script can call App.CreateObject()
. Your CreateObject()
implementation can then create the real requested object and hook up event handlers to it as needed. To fire events back into the script, use the IActiveScript.GetScriptDispatch()
method to retrieve an IDispatch
for the desired procedure defined in the script, and then use IDispatch.Invoke()
with DISPID 0 and the DISPATCH_METHOD
flag to execute that procedure with the desired input parameters.
Your object can implement any properties and methods that you want the script to have access to.
answered Feb 4, 2016 at 6:19
Remy LebeauRemy Lebeau
534k30 gold badges442 silver badges748 bronze badges
The reason your script is failing is due to a few occurrences.
- DO NOT use «
WScript
» as an object especially while coding inWindows-Based Script Host
(orWSH
), as the program assumes you are runningwscript.exe
or callingWScript
commands. - Use
Dim
! If the first rule wasn’t null, this is why. Using command «Option Explicit
» in VBScript requires users toDim
anyobject
or calling of anobject
.
A fixed code would be:
Option Explicit
Dim 1, 2
Set 1 = WScript.CreateObject("WScript.Shell")
Set 2 = WScript.CreateObject("ObjectTest", "pref_")
answered Feb 23, 2021 at 3:05
- Remove From My Forums
-
Question
-
My codes is the following:
Set WshShell = CreateObject(«WScript.Shell»)
WshShell.Run «calc»
WScript.Sleep 100
WshShell.AppActivate «Calculator»
WScript.Sleep 100
……..
When run to the step «WScript.Sleep 100», the error will appear «Object required:’wscript’». I don’t know why the error appear, I think my codes should not have problem, Please help me solve the problem, I will thank you very much.
Remark: The question is posted other forums, other guys tell me the wscript.exe may be not installed on my system at C:WINDOWSsystem32, but I checked the directory, I found the wscript.exe file, so I don’t know why the error appear when run the
codes. the error also appear on other computers.
Answers
-
I’m sorry, but I don’t know what QTP is. I googled it and found a reference to an HP Quick Test Pro. If that’s it, the problem is probably that it is trying to run your script under IE, rather than the Wscript Host. That is, the WScript
object is only instantiated by Wscript.exe or cscript.exe (the two WHS host programs). VBS in IE or as an HTA does not support that object. Your script must be executed as a standalone .VBS or .WSH file to use the Sleep function (and ECHO).At least, that’s my best guess at what the problem could be.
Tom Lavedas
- Marked as answer by
Friday, September 2, 2011 1:29 AM
- Marked as answer by
- Remove From My Forums
-
Question
-
My codes is the following:
Set WshShell = CreateObject(«WScript.Shell»)
WshShell.Run «calc»
WScript.Sleep 100
WshShell.AppActivate «Calculator»
WScript.Sleep 100
……..
When run to the step «WScript.Sleep 100», the error will appear «Object required:’wscript’». I don’t know why the error appear, I think my codes should not have problem, Please help me solve the problem, I will thank you very much.
Remark: The question is posted other forums, other guys tell me the wscript.exe may be not installed on my system at C:WINDOWSsystem32, but I checked the directory, I found the wscript.exe file, so I don’t know why the error appear when run the
codes. the error also appear on other computers.
Answers
-
I’m sorry, but I don’t know what QTP is. I googled it and found a reference to an HP Quick Test Pro. If that’s it, the problem is probably that it is trying to run your script under IE, rather than the Wscript Host. That is, the WScript
object is only instantiated by Wscript.exe or cscript.exe (the two WHS host programs). VBS in IE or as an HTA does not support that object. Your script must be executed as a standalone .VBS or .WSH file to use the Sleep function (and ECHO).At least, that’s my best guess at what the problem could be.
Tom Lavedas
- Marked as answer by
Friday, September 2, 2011 1:29 AM
- Marked as answer by
- Сообщения
- 350
- Реакции
- 365
-
#1
Если я запускаю скрипт VBS из проводника — все нормально, в коде можно использовать объект Wscript
Если его же запускаю из-под Indesign (палитра Сценарии) :
—————————
Adobe InDesign
—————————
Сценарии Windows Ошибка!Номер ошибки: 424
Сообщение об ошибке: Требуется объект: ‘WScript’
Погуглил, не нашел, как создать объект WScript (ведь при «обычном» запуске скриптов он создается автоматически).
Как его можно создать?
- Сообщения
- 7 580
- Реакции
- 3 346
-
#2
ну наверное как-то
set WshShell = WScript.CreateObject(«WScript.Shell»)
- Сообщения
- 350
- Реакции
- 365
-
#3
ну наверное как-то
set WshShell = WScript.CreateObject(«WScript.Shell»)
Совсем не то, хотя WshShell — объект из того же «комплекта»
Тем более, сами видите, что в коде вы уже используете объект «WScript» до его создания — «WScript.CreateObject»
Этот код при запуске сценария из палитры Сценарии работать не будет (но будет работать при запуске из-под Проводника)
iye 0 / 0 / 0 Регистрация: 17.07.2014 Сообщений: 3 |
||||||||
1 |
||||||||
VBS Ошибка: «Требуется объект»17.07.2014, 10:33. Показов 12502. Ответов 6 Метки нет (Все метки)
Добрый день.
XML, который парсится:
Ошибка которая выдается : Что я делаю не так ? Заранее благодарен за ответы.
__________________ 0 |
Eva Rosalene Pure Free Digital Ghost 4598 / 1910 / 370 Регистрация: 06.01.2013 Сообщений: 4,564 |
||||||||
17.07.2014, 13:46 |
2 |
|||||||
В 6 строке:
Добавлено через 19 минут Поэтому либо используйте такую проверку на результат выполнения selectSingleNode: [Ошибочка вышла. Err.Number тоже не работает Либо используйте JS где проверка на равенство null очень даже выполняется:
0 |
0 / 0 / 0 Регистрация: 17.07.2014 Сообщений: 3 |
|
17.07.2014, 15:38 [ТС] |
3 |
Вроде как Null то там не может быть… или я как то не правильно беру строку ? 0 |
Pure Free Digital Ghost 4598 / 1910 / 370 Регистрация: 06.01.2013 Сообщений: 4,564 |
|
17.07.2014, 15:49 |
4 |
iye, по докам с MSDN метод возвращает Null если не может найти элемент. Ваш запрос я чуток подправил, теперь в скинутом вами XML файле скрипт отработает. Но если натравить его на файл с другой структорой, он вылетит с ошибкой. 0 |
0 / 0 / 0 Регистрация: 17.07.2014 Сообщений: 3 |
|
17.07.2014, 16:10 [ТС] |
5 |
Спасибо! Разобрался ) Все что было нужно — добавить 2 слеша в set subnode=node.SelectSingleNode(«item/Name») чтобы получилось set subnode=node.SelectSingleNode(«//item/Name») 0 |
17951 / 7587 / 889 Регистрация: 25.12.2011 Сообщений: 11,317 Записей в блоге: 17 |
|
17.07.2014, 16:15 |
6 |
FraidZZ, Null будет если переменная имеет тип Object, Поэтому правильнее делать проверку через одну из этих функций. 1 |
Eva Rosalene Pure Free Digital Ghost 4598 / 1910 / 370 Регистрация: 06.01.2013 Сообщений: 4,564 |
||||
17.07.2014, 17:04 |
7 |
|||
Dragokas, вот оно как значит. Впрочем, isEmpty я тоже пробовал. И с нулем сравнивал, да. Единственное, что получилось, так это:
0 |
- Сообщения
- 350
- Реакции
- 365
-
#1
Если я запускаю скрипт VBS из проводника — все нормально, в коде можно использовать объект Wscript
Если его же запускаю из-под Indesign (палитра Сценарии) :
—————————
Adobe InDesign
—————————
Сценарии Windows Ошибка!Номер ошибки: 424
Сообщение об ошибке: Требуется объект: ‘WScript’
Погуглил, не нашел, как создать объект WScript (ведь при «обычном» запуске скриптов он создается автоматически).
Как его можно создать?
- Сообщения
- 7 663
- Реакции
- 3 391
-
#2
ну наверное как-то
set WshShell = WScript.CreateObject(«WScript.Shell»)
- Сообщения
- 350
- Реакции
- 365
-
#3
ну наверное как-то
set WshShell = WScript.CreateObject(«WScript.Shell»)
Совсем не то, хотя WshShell — объект из того же «комплекта»
Тем более, сами видите, что в коде вы уже используете объект «WScript» до его создания — «WScript.CreateObject»
Этот код при запуске сценария из палитры Сценарии работать не будет (но будет работать при запуске из-под Проводника)