vbs Variable is Undefined: 'objObject' - arrays

Ok my problem here is that I'm getting a Variable is undefined: 'objObject' error at line 39 char 4. All is good if I remove lines 39-46 but the purpose of the code is to reformat the output from echoing the object which looks like this z:\\\\BAIBOA\\test.txt and change it into a string that looks like this z:\BAIBOA\test.txt to be used later in the code. This code has been edited from another source so maybe I'm not fully understanding what's going on. Any help would be greatly appreciated.
Option Explicit
Dim arrFolders, strComputer, objWMIService, strFolder, strCommand
Dim i, strQuery, strNewFile, arrNewFile, strFilePath, strTempFilePath
Dim colMonitoredEvents, strQueryFolder
arrFolders = Array("Z:\\\\test1", "Z:\\\\test2", "Z:\\\\test2")
strComputer = "."
'strQueryFolder = Replace(strFolder, "\", "\\\\")
Set objWMIService = GetObject("winmgmts:\\" & strComputer _
& "\root\CIMV2")
'Loop through the array of folders setting up the monitor for Each
i = 0
For Each strFolder In arrFolders
'Create the event sink
strCommand = "Set EventSink" & i & " = WScript.CreateObject" & _
"(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")"
ExecuteGlobal strCommand
'Setup Notification
strQuery = "SELECT * FROM __InstanceCreationEvent WITHIN 10 " & _
"WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" & _
" and TargetInstance.GroupComponent = " & _
"'Win32_Directory.Name=""" & strFolder & """'"
strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & _
i & ", strQuery"
ExecuteGlobal strCommand
'Create the OnObjectReady Sub
strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & _
"objAsyncContext)" & VbCrLf & vbTab & _
"Wscript.Echo objObject.TargetInstance.PartComponent" & _
VbCrLf & "End Sub"
'WScript.Echo strCommand
ExecuteGlobal strCommand
i = i + 1
---> Line 39 Set objLatestEvent = objObject.TargetInstance.PartComponent
strNewFile = objLatestEvent.TargetInstance.PartComponent
arrNewFile = Split(strNewFile, "=")
strFilePath = arrNewFile(1)
strFilePath = Replace(strFilePath, "\\", "\")
strFilePath = Replace(strFilePath, Chr(34), "")
strFileName = Replace(strFilePath, strFolder, "")
'strTempFilePath = WScript.CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\TEMP.M4A"
Wscript.Echo strFilePath
Next
WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend
Ok Ive came up with a solution for the output but now im stuck getting the script to increment correctly and will only goto the next folder if the first folder gets a file. What i need is for it to scan the array for new files not 1 by 1. :( any suggestions
Option Explicit
Dim arrFolders, strComputer, objWMIService, strFolder, strCommand
Dim i, strQuery, strNewFile, arrNewFile, strFilePath, strTempFilePath
Dim colMonitoredEvents, strQueryFolder, objObject, objLatestEvent
Dim strFileName
arrFolders = Array("Z:\\\\test1", "Z:\\\\test2", "Z:\\\\test2")
strComputer = "."
i = 0
For Each strFolder In arrFolders
'trQueryFolder = Replace(strFolder, "\", "\\\\")
strQueryFolder = strFolder
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colMonitoredEvents = objWMIService.ExecNotificationQuery ("SELECT * FROM __InstanceCreationEvent WITHIN 10 " & " WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent='Win32_Directory.Name=""" & strQueryFolder & """'")
Wscript.Echo strQueryFolder
'Do
Set objLatestEvent = colMonitoredEvents.NextEvent
strNewFile = objLatestEvent.TargetInstance.PartComponent
arrNewFile = Split(strNewFile, "=")
strFilePath = arrNewFile(1)
strFilePath = Replace(strFilePath, "\\", "\")
strFilePath = Replace(strFilePath, Chr(34), "")
strFileName = Replace(strFilePath, strFolder, "")
strTempFilePath = WScript.CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\TEMP.M4A"
' DO THE OPERATION STUFF
' ...
'Wscript.Echo objLatestEvent.TargetInstance.PartComponent
Wscript.Echo strFilePath
' If strFileName = strQueryFolder then i = i + 1 Else
'Loop
i = i + 1
Next
'WScript.Echo "Waiting for events..."
i = 0
While (True)
Wscript.Sleep(1000)
Wend

Related

ADO recordset getstring slow for large recordsets

I'm using ADO in VBScript. The query is simple and completes in a couple of seconds.
However, when I execute the GetString method, it takes a very long time to complete and sometimes never completes at all.
Set oShell = CreateObject( "WScript.Shell" )
user = oShell.ExpandEnvironmentStrings("%UserName%")
ConnectSqlServer "select top 100000 * from notices FOR JSON AUTO, INCLUDE_NULL_VALUES;", "PSQL003"
Sub ConnectSqlServer(query, database)
On Error Resume Next
sConnString = "Provider=SQLOLEDB.1;Data Source= " & database & "; " & _
"Initial Catalog=VIEW;" & _
"Integrated Security=SSPI;"
MakeConnectionString = "DSN=" & sDSN & ";Uid=" & sUid & ";Pwd=" & sPwd & ";"
Dim conn
Dim rs
Dim sConnString
Dim resultString
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
conn.Open sConnString
conn.CommandTimeout = 0
Set rs = conn.Execute(query)
Set Errs1 = conn.Errors
For Each errLoop In Errs1
With errLoop
StrTmp = StrTmp & "Error #" & i & ":"
StrTmp = StrTmp & vbCrLf & " ADO Error #" & .Number
StrTmp = StrTmp & vbCrLf & " Description " & .Description
StrTmp = StrTmp & vbCrLf & " Source " & .Source
i = i + 1
End With
Next
Msgbox "Query Finished"
resultString = rs.GetString
Msgbox "String Created"
End Sub

Array transpose work with a (10, 1) and not with a (1, 10) array

I am trying to send email to multiple addresses, through a array on the .To, was reading the email addresses in range P2:Z2, and the code wasn't working, i changed the range to M1:M10, and the code worked just fine, what the change that i have to make to function in a (1, 10) arrangement?
Sub EnvioEmail()
Range("B4:K34").ExportAsFixedFormat xlTypePDF, Sheets("Aviso").TextBox1.Text & "\" & Sheets("Aviso").Range("P3").Value
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
Dim EmailTo As String
EmailTo = Join(Application.Transpose(Sheets("Aviso").Range("M1:M10").Value), ";")
With OutMail
.To = EmailTo
.CC = ""
.BCC = ""
.Subject = "Aviso de Cobrança de Aluguel e Encargos " & Sheets("Aviso").Range("P3").Text
.Body = "Prezados, " & _
vbNewLine & vbNewLine & _
"Segue em anexo o aviso de cobrança." & _
vbNewLine & vbNewLine & _
"Atenciosamente, "
.Attachments.Add Sheets("Aviso").TextBox1.Text & "\" & Sheets("Aviso").Range("P3").Value & ".pdf"
.Display
End With
End Sub

Using array for shorter code

I have the same line Repeating many times with small changes. i like to shorten it by using an array of objects
For example, instead of this code:
StartUpdateStr = "Update tblAfterSale SET "
EndUpdateStr = " WHERE IDAfterSale = "
IDAfterSale = Me.lblIDAfterSale.Caption
db.Execute StartUpdateStr & "Data1 = " & Me.Lable1.Caption & EndUpdateStr & IDAfterSale
db.Execute StartUpdateStr & "Data2 = " & Me.Lable2.Caption & EndUpdateStr & IDAfterSale
db.Execute StartUpdateStr & "Data3 = " & Me.Lable3.Caption & EndUpdateStr & IDAfterSale
db.Close
I'm looking for something like this:
Const dCaption = "Me.Lable1.Caption,Me.Lable2.Caption,Me.Lable3.Caption"
Public d(2) As Integer
Public Sub MyMacro()
Dim vntTemp As Variant
Dim intIndex As Integer
vntTemp = Split(lCaption, "d")
For intIndex = 0 To 2
db.Execute StartUpdateStr & "Data"& intIndex & " = " & d(intIndex) & EndUpdateStr & IDAfterSale
Next
End Sub
Can someone write me the right syntax?
Thank you
You can simply access the labels by name with Me("Label" & i)
For intIndex = 0 To 2
db.Execute StartUpdateStr & "Data" & intIndex & " = " _
& Me("Label" & (intIndex + 1)).Caption _
& EndUpdateStr & IDAfterSale
Next
I suppose you will be adding many labels in future. So can you use the below code
Private Sub PrintAllLabel()
For Each ctl In Me.Controls
If TypeName(ctl) = "Label" Then
db.Execute StartUpdateStr & "Data" & intIndex & " = " _
& ctl.Caption _
& EndUpdateStr & IDAfterSale
End If
Next ctl
End Sub

Update Access front end through batch file?

Looking to see if there would be a way for users to update their MS Access db front end by clicking a button. The button would then trigger a batch file that would grab the file from a location on our server, and overwrite the current db on the users local PC. All done within one office, so network addresses would be all the same.
Location of file to copy: 10.0.0.0.5/Data/DB/Database.accdb
Location of file to overwrite: c:\DB\Database.accdb
Any ideas? Ideally I would love for someone to write a nice exe file that deletes the older version and installs the newer version, but can't write that kind of code.
Write a batch file to retrieve the newer version of the front end from it's source and copy it into the folder where the user's copy of the front end file lives. Add a line at the end of the batch file to launch msacess.exe with the filename of your front end program as a command line parameter.
The batch file can be located anywhere, but I recommend locating it in the folder where your application front end will reside.
Create a Windows shortcut to the batch file, which can be placed on the users' Desktop or anywhere else the user expects to launch the application.
Bonus points for dressing up the shortcut to the batch file by changing the icon: Right-click|Properties|Change icon... button.
A nice article on the topic can be found here:
Deploy and update a Microsoft Access application in a Citrix environment
It uses neither a bat, nor an exe, but a VBscript:
Option Explicit
' Launch script for PPT test/development/operation.
' Version 1.3.0
' 2013-09-15
' Cactus Data. Gustav Brock
Const DESKTOP = &H10
Const LOCALAPPDATA = &H1C
Dim objFSO
Dim objAppShell
Dim objDesktopFolder
Dim objLocalAppDataFolder
Dim objLocalFolder
Dim objRemoteFolder
Dim strLocalFolder
Dim strRemoteFolder
Dim strDesktopFolder
Dim strLocalAppDataFolder
Dim strLocalAppDataDsgFolder
Dim strLocalAppDataDsgPptFolder
Dim strDsgSubfolder
Dim strPptSubfolder
Dim strPptAppSubfolder
Dim strPptNcSuffix
Dim strAppName
Dim strAppSuffix
Dim strShortcutName
Dim strAppLocalPath
Dim strAppLocalBackPath
Dim strAppRemotePath
Dim strShortcutLocalPath
Dim strShortcutRemotePath
Dim strRegPath
Dim strRegKey
Dim strRegValue
Dim booNoColour
Dim varValue
' Adjustable parameters.
strDsgSubfolder = "DSG"
strPptSubfolder = "PPT"
strPPtNcSuffix = "NC"
' ---------------------------------------------------------------------------------
' Uncomment one folder name only:
'strPptAppSubfolder = "Development"
strPptAppSubfolder = "Operations"
'strPptAppSubfolder = "Test"
' ---------------------------------
' Indicate if the script is for the normal version (0) or the no-colour version (1):
booNoColour = 0
' ---------------------------------------------------------------------------------
strRemoteFolder = "K:\_Shared\Sales Planning\Environments\" & strPptAppSubfolder
If booNoColour = 1 Then
strAppSuffix = strPptNcSuffix
Else
strAppSuffix = ""
End If
strAppName = "SalesPlanningTool" & strAppSuffix & ".accdb"
If strPptAppSubfolder = "Operations" Then
If strAppSuffix = "" Then
strShortcutName = "RunPPT.lnk"
Else
strShortcutName = "RunPPT " & strAppSuffix & ".lnk"
End If
Else
If strAppSuffix = "" Then
strShortcutName = "RunPPT " & strPptAppSubfolder & ".lnk"
Else
strShortcutName = "RunPPT " & strAppSuffix & " " & strPptAppSubfolder & ".lnk"
End If
End If
' Enable simple error handling.
On Error Resume Next
' Find user's Desktop and AppData\Local folder.
Set objAppShell = CreateObject("Shell.Application")
Set objDesktopFolder = objAppShell.Namespace(DESKTOP)
strDesktopFolder = objDesktopFolder.Self.Path
Set objLocalAppDataFolder = objAppShell.Namespace(LOCALAPPDATA)
strLocalAppDataFolder = objLocalAppDataFolder.Self.Path
' Dynamic parameters.
strLocalAppDataDsgFolder = strLocalAppDataFolder & "\" & strDsgSubfolder
strLocalAppDataDsgPptFolder = strLocalAppDataDsgFolder & "\" & strPptSubfolder
strLocalFolder = strLocalAppDataDsgPptFolder & "\" & strPptAppSubfolder
strAppLocalPath = strLocalFolder & "\" & strAppName
strShortcutLocalPath = strDesktopFolder & "\" & strShortcutName
' Permanent parameters.
strAppRemotePath = strRemoteFolder & "\" & strAppName
strShortcutRemotePath = strRemoteFolder & "\" & strShortcutName
' Create the File System Object.
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strRemoteFolder) Then
Call ErrorHandler("No access to " & strRemoteFolder & ".")
Else
Set objRemoteFolder = objFSO.GetFolder(strRemoteFolder)
' If local folder does not exist, create the folder.
If Not objFSO.FolderExists(strLocalFolder) Then
If Not objFSO.FolderExists(strLocalAppDataDsgFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalAppDataDsgFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalAppDataDsgFolder & " could not be created.")
End If
End If
If Not objFSO.FolderExists(strLocalAppDataDsgPPtFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalAppDataDsgPptFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalAppDataDsgPptFolder & " could not be created.")
End If
End If
If Not objFSO.FolderExists(strLocalFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalFolder & " could not be created.")
End If
End If
End If
Set objLocalFolder = objFSO.GetFolder(strLocalFolder)
End If
If Not objFSO.FileExists(strAppRemotePath) Then
Call ErrorHandler("The application file:" & vbCrLf & strAppRemotePath & vbCrLF & "could not be found.")
Else
' Close a running PPT.
Call KillTask("PPT")
' Wait while TaskKill is running twice to close the instance(s) of PPT and PPT Background.
Call AwaitProcess("taskkill.exe")
Call KillTask("PPT Background")
' Wait while TaskKill is running twice to close the instance(s) of PPT and PPT Background.
Call AwaitProcess("taskkill.exe")
' Copy app to local folder.
If objFSO.FileExists(strAppLocalPath) Then
objFSO.DeleteFile(strAppLocalPath)
If Not Err.Number = 0 Then
Call ErrorHandler("The application file:" & vbCrLf & strAppName & vbCrLF & "can not be refreshed/updated. It may be in use.")
End If
End If
If objFSO.FileExists(strAppLocalPath) Then
Call ErrorHandler("The local application file:" & vbCrLf & strAppLocalPath & vbCrLF & "could not be replaced.")
Else
objFSO.CopyFile strAppRemotePath, strAppLocalPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Application could not be copied to " & strLocalFolder & ".")
End If
' Create copy for PPT Background.
strAppLocalBackPath = Replace(Replace(strAppLocalPath, ".accdb", ".accbg"), "SalesPlanningTool", "SalesPlanningToolBack")
objFSO.CopyFile strAppLocalPath, strAppLocalBackPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Background application could not be copied to " & strLocalFolder & ".")
End If
End If
' Copy shortcut.
objFSO.CopyFile strShortcutRemotePath, strShortcutLocalPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Shortcut could not be copied to your Desktop.")
End If
End If
' Write Registry entries for Access security.
strRegKey = "HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\"
strRegValue = "VBAWarnings"
strRegPath = strRegKey & strRegValue
varValue = 1
Call WriteRegistry(strRegPath, varValue,"REG_DWORD")
strRegKey = strRegKey & "Trusted Locations\LocationLocalAppData\"
strRegValue = "AllowSubfolders"
strRegPath = strRegKey & strRegValue
varValue = 1
Call WriteRegistry(strRegPath, varValue, "REG_DWORD")
strRegValue = "Date"
strRegPath = strRegKey & strRegValue
varValue = Now
varValue = FormatDateTime(varValue, vbShortDate) & " " & FormatDateTime(varValue, vbShortTime)
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
strRegValue = "Description"
strRegPath = strRegKey & strRegValue
varValue = "Local AppData"
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
strRegValue = "Path"
strRegPath = strRegKey & strRegValue
varValue = strLocalAppDataFolder & "\"
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
' Run PPT.
If objFSO.FileExists(strAppLocalPath) Then
Call RunApp(strAppLocalPath, False)
Else
Call ErrorHandler("The local application file:" & vbCrLf & strAppLocalPath & vbCrLF & "could not be found.")
End If
Set objRemoteFolder = Nothing
Set objLocalFolder = Nothing
Set objLocalAppDataFolder = Nothing
Set objDesktopFolder = Nothing
Set objAppShell = Nothing
Set objFSO = Nothing
WScript.Quit
' Supporting subfunctions
' -----------------------
Sub RunApp(ByVal strFile, ByVal booBackground)
Dim objShell
Dim intWindowStyle
' Open as default foreground application.
intWindowStyle = 1
Set objShell = CreateObject("WScript.Shell")
objShell.Run Chr(34) & strFile & Chr(34), intWindowStyle, False
Set objShell = Nothing
End Sub
Sub KillTask(ByVal strWindowTitle)
Dim objShell
Set objShell = CreateObject("WScript.Shell")
objShell.Run "TaskKill.exe /FI ""WINDOWTITLE eq " & strWindowTitle & """", 7, False
Set objShell = Nothing
End Sub
Sub AwaitProcess(ByVal strProcess)
Dim objSvc
Dim strQuery
Dim colProcess
Dim intCount
Set objSvc = GetObject("winmgmts:root\cimv2")
strQuery = "select * from win32_process where name='" & strProcess & "'"
Do
Set colProcess = objSvc.Execquery(strQuery)
intCount = colProcess.Count
If intCount > 0 Then
WScript.Sleep 300
End If
Loop Until intCount = 0
Set colProcess = Nothing
Set objSvc = Nothing
End Sub
Sub WriteRegistry(ByVal strRegPath, ByVal varValue, ByVal strRegType)
' strRegType should be:
' "REG_SZ" for a string
' "REG_DWORD" for an integer
' "REG_BINARY" for a binary or boolean
' "REG_EXPAND_SZ" for an expandable string
Dim objShell
Set objShell = CreateObject("WScript.Shell")
Call objShell.RegWrite(strRegPath, varValue, strRegType)
Set objShell = Nothing
End Sub
Sub ErrorHandler(Byval strMessage)
Set objRemoteFolder = Nothing
Set objLocalFolder = Nothing
Set objLocalAppDataFolder = Nothing
Set objDesktopFolder = Nothing
Set objAppShell = Nothing
Set objFSO = Nothing
WScript.Echo strMessage
WScript.Quit
End Sub
You could probably convert it to PowerShell, which I would use today.
I use a vbscript for that purpose. I only update the path for the file due to be copied and then I sent an email to the users with a link to the script. The user clicks the link and the script is executed.
Copy the code below to a text file and save it as .vbs. Don't forget to set the path for the file due to be copied.
Option Explicit
Call Main()
Private Sub Main()
const folderFrom = "\\Somepath\Somefolder\" 'Folder: Must supply backslash
const fileName = "SomeFile.accdb" 'File name with extension
const overwrite = -1 'OverWrite = True
'Ask user to proceed
dim msg
msg = "The script will copy the file below to your desktop. " & vbNewLine & vbNewLine & _
String(75,"_") & vbNewLine & vbNewLine & _
"File: " & " " & " " & " " & " " & " " & " " & " '" & fileName & "' " & vbNewLine & _
"Folder: " & " " & " '" & folderFrom & "' " & vbNewLine & _
String(75,"_") & vbNewLine & vbNewLine & _
"Proceed?"
if MsgBox(msg, vbYesNo + vbQuestion, "FileCopy Confirmation") = vbNo then exit sub
on error resume next
dim filesys
set filesys = CreateObject("Scripting.FileSystemObject")
'File exists in folder?
if not filesys.FileExists(folderFrom & fileName) then
MsgBox "File not found. Task aborted. ", vbOKOnly + vbExclamation, "Attention:"
exit sub
end if
'User's desktop path
dim desktopPath
desktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
'Copy file
filesys.CopyFile folderFrom & fileName, desktopPath & fileName, overwrite
'Validate file copied
if filesys.FileExists(desktopPath & fileName) then
Msgbox "File copied successfully.", vbOKOnly + vbInformation, "Success!"
else
MsgBox "File could not be copied... ", vbOKOnly + vbExclamation, "Copy Failed..."
end if
End Sub
Suggestion:
You shouldn't overwrite the existing front-end database but instead you should consider versioning e.g. v2.0, v2.1, v2.2 etc. for better tracking.

Microsoft VBScript compilation error: Expected statement

What is wrong with this script?
Option Explicit
Dim objRootDSE, strDNSDomain, adoConnection
Dim strBase, strFilter, strAttributes, strQuery, adoRecordset
Dim dtmStart, dtmEnd, strStart, strEnd
Dim strID, strFirst, strLast, strNTName
dtmEnd = Now()
dtmStart = DateAdd("d", -7, dtmEnd)
strStart = CStr(Year(dtmStart)) _
& Right("0" & CStr(Month(dtmStart)), 2) _
& Right("0" & CStr(Day(dtmStart)), 2) & "000000.0Z"
strEnd = CStr(Year(dtmEnd)) _
& Right("0" & CStr(Month(dtmEnd)), 2) _
& Right("0" & CStr(Day(dtmEnd)), 2) & "235959.0Z"
' Determine DNS domain name.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
' Use ADO to search Active Directory.
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoRecordset = CreateObject("ADODB.Recordset")
adoRecordset.ActiveConnection = adoConnection
' Search entire domain.
strBase = "<LDAP://" & strDNSDomain & ">"
'For user accounts for people created in the last week
strFilter = "(&(objectCategory=person)(objectClass=user)" _
& "(whenCreated>=" & strStart & ")(whenCreated<=" & strEnd & "))"
' Comma delimited list of attribute values to retrieve.
strAttributes = "employeeID,sn,givenName,sAMAccountName"
' Construct the LDAP query.
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
' Run the query.
adoRecordset.Source = strQuery
adoRecordset.Open
' Enumerate the resulting recordset.
Do Until adoRecordset.EOF
' Retrieve values.
strID = adoRecordset.Fields("employeeID").Value
strLast = adoRecordset.Fields("sn").Value
strFirst = adoRecordset.Fields("givenName").Value
strNTName = adoRecordset.Fields("sAMAccountName").Value
Wscript.Echo """" & strID & """,""" & strLast & """,""" & strFirst
& """,""" & strNTName & """"
adoRecordset.MoveNext
Loop
' Clean up.
adoRecordset.Close
adoConnection.Close
cscript //nologo test.vbs > users.csv
returns
(53, 1) Microsoft VBScript compilation error: Expected statement
You're missing an underscore line continuation at the end of the first line of this snippet:
Wscript.Echo """" & strID & """,""" & strLast & """,""" & strFirst
& """,""" & strNTName & """"
It should look like this:
Wscript.Echo """" & strID & """,""" & strLast & """,""" & strFirst _
& """,""" & strNTName & """"

Resources