Ошибка компиляции microsoft vbscript предполагается наличие окончания инструкции

I am trying to insert some records into MS Access Table with the help of below VB Script. But when am trying to execute it, it’s throwing Compilation error: Expected end of statement. Could someone please help me figure out where am I going wrong.

Private Sub Form_Click()
Dim dbs         As DAO.Database
Dim DbFullNAme  As String

DbFullName = "D:GDiamondFINAL MS-AccessMS-Access project.accdb"
Set dbs = OpenDatabase(DbFullName)

dbs.Execute "INSERT INTO [2014_Status] ( Prompt, Project_Name, STATUS,Release_Name )SELECT     RoadMap.SPRF_CC, RoadMap.SPRF_Name, RoadMap.Project_Phase,RoadMap.Release_Name FROM RoadMap WHERE (((Exists (select 1 FROM [2014_Status] where RoadMap.SPRF_CC = [2014_Status].[Prompt]))=False));"
dbs.Close
End Sub

Pankaj Jaju's user avatar

Pankaj Jaju

5,3212 gold badges25 silver badges41 bronze badges

asked Apr 23, 2014 at 17:14

user2412576's user avatar

6

VBScript (as opposed to VBA or other dialects) does not support typed Dims. So

Dim dbs         As DAO.Database
Dim DbFullNAme  As String

need to be

Dim dbs
Dim DbFullNAme

VBscript has no native OpenDatabase() function. You need to use ADO to connect to your Access ‘database’. First create a connection

Set dbs = CreateObject("ADODB.Connection")

Then determine the connection string and

dbs.Open cs

The rest of your code should work.

Update wrt comment:

The error message:

D:GDiamondFINAL MS-Accessquery1.vbs(2, 9) Microsoft VBScript compilation error: Expected end of statement

prooves that the OT tried to write a VBScript (the addition of the misleading vba/access tags is (C) Pankaj Jaju).

answered Apr 23, 2014 at 17:29

Ekkehard.Horner's user avatar

Ekkehard.HornerEkkehard.Horner

38.3k2 gold badges44 silver badges94 bronze badges

3

So lets break down the real reason why this code doesn’t work.

You copied and pasted Visual Basic for Applications(VBA) into a .VBS(Visual Basic Script) file and expected it to work, I assume.

The problem with this is that VBA and VBScript are slightly different languages. Review the info section for both tags on stackoverflow when you get the opportunity.

For now lets just patch your code and maintain your DAO object so you don’t have to reconstruct your Database usage with ADODB.

ExecuteInsert
Sub ExecuteInsert()
    Dim dbs, DbFullName, acc
    Set acc = createobject("Access.Application")

    DbFullName = "D:GDiamondFINAL MS-AccessMS-Access project.accdb"
    Set dbs = acc.DBEngine.OpenDatabase(DbFullName, False, False)
    dbs.Execute "INSERT INTO [2014_Status] ( Prompt, Project_Name, STATUS,Release_Name )SELECT     RoadMap.SPRF_CC, RoadMap.SPRF_Name, RoadMap.Project_Phase,RoadMap.Release_Name FROM RoadMap WHERE (((Exists (select 1 FROM [2014_Status] where RoadMap.SPRF_CC = [2014_Status].[Prompt]))=False));"
    dbs.Close
    msgbox "done"
End Sub

Changes made.

  1. Blocked your dim’d variables and removed As *** statements for vbscript compatibility
  2. Set an access object so you could maintain the remainder of your code.
  3. Added the acc.DBEngine. before OpenDatabase with additional parameters.
  4. Renamed your Sub from Form_Click to ExecuteInsert, then placed ExecuteInsert at the top of the code so that the vbscript activates the sub. If you just place a sub in a vbscript file, it will not necessarily run, you have to activate it directly.

This code is tested and functions. Best of luck to you.

answered Apr 23, 2014 at 19:20

Rich's user avatar

RichRich

4,0943 gold badges26 silver badges44 bronze badges

1

Adding to Ekkehard.Horner
http://www.csidata.com/custserv/onlinehelp/vbsdocs/vbs6.htm

VBScript has only one data type called a Variant. A Variant is a
special kind of data type that can contain different kinds of
information, depending on how it’s used. Because Variant is the only
data type in VBScript, it’s also the data type returned by all
functions in VBScript.

answered Apr 23, 2014 at 17:32

0

Студворк — интернет-сервис помощи студентам

Есть скрипт:

Visual Basic
1
2
3
4
5
6
7
8
9
Set FSO = CreateObject("Scripting.FileSystemObject")
Set WshNetwork = WScript.CreateObject("WScript.Network")
LotusPath = "C:Users" & WshNetwork.UserName & "Lotus"
 
'Проверяем наличие папки Lotus в перемещаемом профиле, если такой папки не существует, то создаем ее
If FSO.FolderExists(LotusPath) = False Then
    FSO.CreateFolder(LotusPath)
    robocopy "C:Program Files (x86)Lotus" "C:Users%USERNAME%Lotus" "notes.ini"
End If

При запуске ругается:
Строка:8
Символ:42
(это буква «L» после «(x86)»)
Ошибка:Предполагается наличие окончания инструкции

Если эту строчку скопировать и запустить в cmd под тем же пользователем, она без проблем отрабатывается.
Что ОНО хочет от меня?

Добавлено через 18 минут
Поправка!Строка:8
Символ:42
(это первый символ второго параметра: «C:Users%USERNAME%Lotus»)

  • Remove From My Forums
  • Question

  • Доброго времени суток.
    В организации на 250+ машинах сетевые параметры адаптеров установлены статикой (sic), необходимо заставить брать их по DHCP. Нашел пару скриптов, наиболее подходящим показался VBS (с которым я совершенно не знаком), т.к.
    другой предполагает указание имени сетевого подключения (например, «Подключение по локальной сети»). Сам скрипт:
    WMIC Path Win32_NetworkAdapterConfiguration Where «IPEnabled = True» Call SetDNSServerSearchOrder 

    WMIC Path Win32_NetworkAdapterConfiguration Where «IPEnabled = True» Call EnableDHCP

    выдает: предполагается наличие окончания инструкции. строка1, символ 11.

    пробовал использовать bat такого вида: 

    netsh interface ip set address name=»Подключение по локальной сети» source=dhcp 

    netsh interface ip set dnsservers name=»Подключение по локальной сети» source=dhcp 

    ощутил проблемы с кодировкой, 1 раз он отработал, хотя отписал козябру, НО я не могу понять как, т.к. повторить я этого не могу, пробовал 1251, 866, 869 — без толку.

    Подскажите что-нибудь пожалуйста.

    • Edited by

      Friday, September 19, 2014 8:19 AM

Answers

  • Как я уже говорил с vbs не сталкивался, решение предложенное в той теме Aleksey.T

    выдает: строка 1, символ 1, несоответствие типа ‘Code’, код: 800A000D

    НО оказывается якобы vbs скрипт который я привел использует обычные команды wmic.exe, которые можно использовать в пакетном файле и это работает. Тема закрыта.

    • Marked as answer by
      Копылов Анатолий
      Friday, September 19, 2014 8:47 AM

Troubleshooting Code 800A0401 – Expected End of Statement

Good news, here is another example of a WSH error message with a helpful Char: number.  Count along the line until you get to the offending character.  With Error 800A0401 start by looking for missing ampersands (&).

Introduction to Code 800A0401

Error code, 800A0401 occurs when you execute a VBScript.  This is a compilation error, therefore check your punctuation.  A wild guess, you have left out an ampersand (&), or possibly a comma.Code 800A0401 - Expected end of statement

The Symptoms You Get

The script does not execute as you had hoped. Instead, Windows Scripting host generates a message box like this picture:  Good news, I have three examples of code: 800A0401.

The Cause of Code 800A0401 VBScript Error

Your VBScript contains a punctuation error.   Note: The clue from Source: Microsoft VBScript compilation error, this means a syntax error in your script.  In this case the Char: number (33) is particularly valuable in troubleshooting.

The Solution to Error: Expected end of statement

Check the syntax of your script, in particular double-check punctuation marks (&, comma, speech marks or full stop.).  In this instance, Windows Scripting Host has detected a mix-up between a comma and a full stop.  As ever, a line number is helpful when troubleshooting, moreover, any Char : number other than 1, will pin-point the problem.

  ‡

Example 1 of Script for Code 800A0401

Note: The error is at Line 3, Character 33 – wbemServices, Instances

It should be wbemServices.Instances  (Full stop, and not a comma)

‘ VBScript Error 800A0401
strComputer = «Alan»
set wbemservices = GetObject(«Winmgmts:\» & strComputer)
set wbemObjectSet = wbemServices, InstancesOf («win32_LogicalMemoryConfiguration»)
For each wbemobject in wbemobjectset
WScript.echo «Tot Physical Memory » & wbemobject.totalPhysicalMemory
Next

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Orion performance monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Example 2 of Script for Error 800A0401

Problem

Wscript.Echo objNetwork.UserName » at » & objNetwork.ComputerName

An & (ampersand) is missing it should be:

Correction

Wscript.Echo objNetwork.UserName & » at » & objNetwork.ComputerName

‘ VBScript 800A0401 Error
Set ObjNetwork = CreateObject(«Wscript.Network»)
Wscript.Echo objNetwork.UserName » at » & objNetwork.ComputerName

[ThemesGuy/google_leader728htm]

Example 3 – Missing Comma

The error is on line 10 char 33, it needs a comma between the drive letter and the UNC path

objNetwork.MapNetworkDrive «R:» «\alanbackup»
objNetwork.MapNetworkDrive «R:» ,  «\alanbackup»

‘ BudgetPear.vbs
‘ Script to map the Budget share on the server pear
‘ Version 1.1 August 2010
‘ Guy Thomas https://computerperformance.co.uk

Option Explicit
Dim objNetwork

Set objNetwork = CreateObject(«Wscript.Network»)
objNetwork.MapNetworkDrive «R:» «\alanbackup»
WSript.echo » Share Mapped «
WScript.Quit

‘ End of Guy’s script

Summary of Error Code 800A0401

As usual with 0800 error codes, check the line number and the char number.  Pay careful attention to any punctuation.  Is there a comma, missing?  Could there be a comma, where the script needs a full stop?

See More Windows Update Error Codes 8004 Series

• Error 800A101A8 Object Required   •Error 800A0046   •Error 800A10AD   •Error 800A000D

• Error 80048820   •Error 800A0401   •Review of SolarWinds Permissions Monitor

• Error 80040E14   • Error 800A03EA   • Error 800A0408   • Error 800A03EE

Solarwinds Free WMI MonitorGuy Recommends: WMI Monitor and It’s Free!

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.  Fortunately, SolarWinds have created the WMI Monitor so that you can examine these gems of performance information for free.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor


Do you need additional help?

  • For interpreting the WSH messages check Diagnose 800 errors.
  • For general advice try my 7 Troubleshooting techniques.
  • See master list of 0800 errors.
  • Codes beginning 08004…
  • Codes beginning 08005…
  • Codes beginning 08007…
  • Codes beginning 0800A…

Give something back?

Would you like to help others?  If you have a good example of this error, then please email me, I will publish it with a credit to you:

If you like this page then please share it with your friends


Решил изучить платформу Nanocad.

Создал файл .VBS и вставил туда код из файла api/ncX_app.chm

Dim nc As New nanoCAD.Application
nc.Utility.Prompt ("Hello CAD!")

Nanocad выдал ошибку:

Script file path или [./]: C:UsersAmk_2Desktopexample.vbserr: "Ошибка компиляции Microsoft VBScript" raised an exception "Предполагается наличие окончания инструкции" at line 1 pos 7
Dim nc As New nanoCAD.Application
      ^

Насколько я помню, VBS является безтиповым языком. Точнее не требует объявления типов.

Поэтому ругается на явное объявление

Dim nc As New nanoCAD.Application

Один из вариантов реализации вашего кода с помощью метода CreateObject

Dim nc
Set nc = CreateObject("nanoCAD.Application")
nc.Utility.Prompt ("Hello CAD!")


Изменено 8 июня, 2011 пользователем shteyn

Понравилась статья? Поделить с друзьями:
  • Флуниджект инструкция по применению для животных крс
  • Руководитель с демократическим стилем руководства наиболее эффективен
  • Краткое руководство по git
  • Киа карнивал мануал 2007
  • Авторитарный стиль руководства курсовая