vbscript close object before set again - vbscript

I have recently inherited a DTS package written in VBScript, i have not had a lot of exposure to VBS and wanted to check if the function where i have added the ' Do i need a rs1.close here comment below should be closing the rs1 object before setting it again?.
Function Proc_Amend()
On error resume next
dtspackagelog.writestringtolog "Start Proc_Amend at " & Time
' Check record to be amended exists
set rs1 = cn1.execute("SELECT StatusFlag from wmLoadId where LoadID='" & iarray(1) & _
"' and OrderNumber='" & iarray(2) & "' and OrderLineNumber='" & iarray(4) & "' and OrderReleaseNumber='" & iarray(5) & "'")
If rs1.eof then
Err.Raise 9994 , , "Record to be amended DOES NOT exist"
Call ErrHand(err.number,err.description)
Else
If UCASE(rs1.fields("StatusFlag").value) = "PENDING" Then
iarray(14) = "PENDING"
End If
' Do i need a rs1.close here
set rs1 = cn1.execute("UPDATE wmLoadId set OrderWeight = " & iarray(9) & ",StatusFlag='" & iarray(14) & "',Timestamp = getdate() where LoadID='" & iarray(1) & _
"' and OrderNumber='" & iarray(2) & "' and OrderLineNumber='" & iarray(4) & "' and OrderReleaseNumber='" & iarray(5) & "'")
If Err Then
' An error occurred so process
Call ErrHand(err.number,err.description)
End If
' Check and update planned_ship_date (if reqd.)
' Do i need a rs1.close here
set rs1 = cn1.execute("SELECT planned_ship_date from Add_Info where LoadID='" & iarray(1) & _
"' and OrderNumber='" & iarray(2) & "' and OrderLineNumber='" & iarray(4) & "' and OrderReleaseNumber='" & iarray(5) & "'")
If rs1.eof then
Err.Raise 9988 , , "No Add_Info record exists to update"
Call ErrHand(err.number,err.description)
Else
cm.CommandText="select convert(varchar(10),wanted_delivery_date,103) AS PlanShip from OPENQUERY(DB33,'select wanted_delivery_date from CUSTOMER_ORDER_LINE_TAB where order_no=''" & iarray(2) & _
"'' and LINE_NO = ''" & iarray(4) & "'' AND REL_NO = ''" & iarray(5) & "'' ' ) "
dtspackagelog.writestringtolog "Planned_Ship_Date (amend) command is " & cm.CommandText
set rs = cm.execute()
dtspackagelog.writestringtolog "Err status after Planned_Ship_Date (amend) command is " & err.number & " at " & Time
if rs.eof then
On Error Resume Next
dtspackagelog.writestringtolog "No CUSTOMER_ORDER record found for order line (amend) at " & Time
Err.Raise 9987 , , "No CUSTOMER_ORDER record found for order line (amend) " & iarray(2) & " / " & iarray(4) & " / " & iarray(5)
Call ErrHand(err.number,err.description)
else
planship = rs.Fields("PlanShip").value
rs.close
End If
dtspackagelog.writestringtolog "PlanShip (amend) set to " & planship & " at " & Time
If rs1.fields("planned_ship_date").value <> planship Then
dtspackagelog.writestringtolog "Update PlanShip from " & rs1.fields("planned_ship_date").value & " to " & planship & " at " & Time
' Do i need a rs1.close here
set rs1 = cn1.execute("UPDATE Add_Info set planned_ship_date = '" & planship & "' where LoadID='" & iarray(1) & _
"' and OrderNumber='" & iarray(2) & "' and OrderLineNumber='" & iarray(4) & "' and OrderReleaseNumber='" & iarray(5) & "'")
If Err Then
' An error occurred so process
Call ErrHand(err.number,err.description)
End If
End If
End If
End If
dtspackagelog.writestringtolog "Finish Proc_Amend at " & Time
End Function

Related

Trigger some vbs code on filename change

I would like to be able run some custom vb script code upon filename change (for instance to keep a list of newly created files or the ones which changed their name).
The vbs should be called on every filename change happening within a specified folder.
I know how to do that with a full directory scan but I would like to find a more efficient method, for instance by the mean of a sort of OS hook calling my code.
Any way to do that ?
Thank you,
A.
There are two simple WMI examples, tracing changes for *.txt files in C:\Test\ folder.
First one is for synchronous event processing:
Option Explicit
Dim oWMIService, oEvents, s
Set oWMIService = GetObject("WinMgmts:\\.\root\CIMv2")
Set oEvents = oWMIService.ExecNotificationQuery( _
"SELECT * FROM __InstanceOperationEvent " & _
"WITHIN 1 WHERE " & _
"TargetInstance ISA 'CIM_DataFile' AND " & _
"TargetInstance.Drive = 'C:' AND " & _
"TargetInstance.Extension = 'txt' AND " & _
"TargetInstance.Path = '\\Test\\'")
Do
With oEvents.NextEvent()
s = "Event: " & .Path_.Class & vbCrLf
With .TargetInstance
s = s & "Name: " & .Name & vbCrLf
s = s & "File Size: " & .FileSize & vbCrLf
s = s & "Creation Date: " & .CreationDate & vbCrLf
s = s & "Last Modified: " & .LastModified & vbCrLf
s = s & "Last Accessed: " & .LastAccessed & vbCrLf
End With
If .Path_.Class = "__InstanceModificationEvent" Then
With .PreviousInstance
s = s & "Previous" & vbCrLf
s = s & "File Size: " & .FileSize & vbCrLf
s = s & "Last Modified: " & .LastModified & vbCrLf
End With
End If
End With
WScript.Echo s
Loop
The second is for asynchronous event processing:
Option Explicit
Dim oWMIService, oSink
Set oWMIService = GetObject("WinMgmts:\\.\root\CIMv2")
Set oSink = WScript.CreateObject("WbemScripting.SWbemSink", "Sink_")
oWMIService.ExecNotificationQueryAsync oSink, _
"SELECT * FROM __InstanceOperationEvent " & _
"WITHIN 1 WHERE " & _
"TargetInstance ISA 'CIM_DataFile' AND " & _
"TargetInstance.Drive = 'C:' AND " & _
"TargetInstance.Extension = 'txt' AND " & _
"TargetInstance.Path = '\\Test\\'"
Do
WScript.Sleep 1000
Loop
Sub Sink_OnObjectReady(oEvent, oContext)
Dim s
With oEvent
s = "Event: " & .Path_.Class & vbCrLf
With .TargetInstance
s = s & "Name: " & .Name & vbCrLf
s = s & "File Size: " & .FileSize & vbCrLf
s = s & "Creation Date: " & .CreationDate & vbCrLf
s = s & "Last Modified: " & .LastModified & vbCrLf
s = s & "Last Accessed: " & .LastAccessed & vbCrLf
End With
If .Path_.Class = "__InstanceModificationEvent" Then
With .PreviousInstance
s = s & "Previous" & vbCrLf
s = s & "File Size: " & .FileSize & vbCrLf
s = s & "Last Modified: " & .LastModified & vbCrLf
End With
End If
End With
WScript.Echo s
End Sub
More info on CIM_DataFile instance properties you can find by the link on MSDN.

Access 2013 Insert / update

I have a form to add user.
I can add, delete rows in the table however I pretend to update if the user already exist.
My goal is press the row in sub form to edit.
but every time I press update it gives me an error.
Run-time error '3075' Syntax error operator in query expression.
the action code I have is this
Private Sub cmdAdd_Click()
'quando se carrega em Adicionar há 2 opcoes
'1-Insert
'2-Update
If Me.txtuserid.Tag & "" = "" Then
'1
CurrentDb.Execute "INSERT INTO user(userid, username, userfunction, usercc) " & _
" VALUES(" & Me.txtuserid & ",'" & Me.txtusername & "','" & Me.txtuserfun & "','" & Me.txtusercc & "')"
Else
'2
CurrentDb.Execute "UPDATE user " & _
" SET userid=" & Me.txtuserid & _
", username=" & Me.txtusername & "'" & _
", userfunction =" & Me.txtuserfun & "'" & _
", usercc =" & Me.txtusercc & "'" & _
" WHERE userid =" & Me.txtuserid.Tag
End If
'clear fields
cmdClear_Click
'refresh
SubForm1.Form.Requery
End Sub
What I'm doing wrong?
Did you miss ' in you update statement;
CurrentDb.Execute "UPDATE user " & _
" SET userid=" & Me.txtuserid & _
", username='" & Me.txtusername & "'" & _
", userfunction ='" & Me.txtuserfun & "'" & _
", usercc ='" & Me.txtusercc & "'" & _
" WHERE userid =" & Me.txtuserid.Tag

Number of query values and destination fields are not the same. Error Message

I'm having an error message with my codes in visual basic. Please help. Thanks.
The error says:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.txtID.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO ProfessorListTable(ID,LastName,FirstName,MI,Gender,Department,ContactNo,Address,EmailAddress,YearEmployed)" & _
" VALUES(" & Me.txtID.Text & ",'" & Me.txtLName.Text & "','" & _
Me.txtFName.Text & "','" & Me.txtMI.Text & "','" & _
Me.txtGender.Text & "','" & Me.txtDept.Text & "','" & _
Me.txtNo.Text & "','" & Me.txtAddress.Text & "','" & _
Me.txtEAdd.Text & "','" & Me.txtYear.Text & "',')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE ProfessorListTable " & _
" SET txtID=" & Me.txtID.Text & _
", LastName='" & Me.txtLName.Text & "'" & _
", FirstName='" & Me.txtFName.Text & "'" & _
", MI='" & Me.txtMI.Text & "'" & _
", Gender='" & Me.txtGender.Text & "'" & _
", Department='" & Me.txtDept.Text & "'" & _
", ContactNo='" & Me.txtNo.Text & _
", Address='" & Me.txtAddress.Text & "'" & _
", EmailAddress='" & Me.txtEAdd.Text & "'" & _
", YearEmployed='" & Me.txtYear.Text & _
" WHERE stdid=" & Me.txtID.Tag
cmd.ExecuteNonQuery()
End If
RefreshData()
End Sub
The
You had extra Comma (,) here
& Me.txtYear.Text & "','
So it's leads to 11 value instead of 10
And Address is reserved word so use it as [Address]
Try like this
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.txtID.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO ProfessorListTable(ID,LastName,FirstName,MI,Gender,Department,ContactNo,[Address],EmailAddress,YearEmployed)" & _
" VALUES(" & Me.txtID.Text & ",'" & Me.txtLName.Text & "','" & _
Me.txtFName.Text & "','" & Me.txtMI.Text & "','" & _
Me.txtGender.Text & "','" & Me.txtDept.Text & "','" & _
Me.txtNo.Text & "','" & Me.txtAddress.Text & "','" & _
Me.txtEAdd.Text & "','" & Me.txtYear.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE ProfessorListTable " & _
" SET txtID=" & Me.txtID.Text & _
", LastName='" & Me.txtLName.Text & "'" & _
", FirstName='" & Me.txtFName.Text & "'" & _
", MI='" & Me.txtMI.Text & "'" & _
", Gender='" & Me.txtGender.Text & "'" & _
", Department='" & Me.txtDept.Text & "'" & _
", ContactNo='" & Me.txtNo.Text & _
", [Address]='" & Me.txtAddress.Text & "'" & _
", EmailAddress='" & Me.txtEAdd.Text & "'" & _
", YearEmployed='" & Me.txtYear.Text & _
" WHERE stdid=" & Me.txtID.Tag
cmd.ExecuteNonQuery()
End If
RefreshData()
End Sub

What's causing Microsoft VBScript runtime error '800a01a8'

I am getting this specific error, help would be appreciated
Microsoft VBScript runtime error '800a01a8'
Object required: 'openRecordSet(...)'
/admin/users/affiliates/process.asp, line 47
Line 47 is Set objRecordset = openRecordset(strSQL, objConnection)
<%
SetUserLevel(" 2 ")
If (InStr(Request.ServerVariables("HTTP_REFERER"), "://jim/admin/users/affiliate") = 0) Then
Response.Redirect( "/admin/users/affiliate/" )
End If
Dim objConnection, objRecordset, strSQL, Affiliate_ID
If (IsEmpty(Request.Form("Affiliate_ID")) Or RTrim(Request.Form("Affiliate_ID")) = "") Then
Affiliate_ID = 0
Else
Affiliate_ID = prepareSQL(Request.Form("Affiliate_ID"))
End If
strSQL = "EXEC sp_User_Add_Affiliate " & _
Session("User_ID") & ", '" & _
prepareSQL(Request.Form("First_Name")) & "', '" & _
prepareSQL(Request.Form("Middle_Initial")) & "', '" & _
prepareSQL(Request.Form("Last_Name")) & "', '" & _
prepareSQL(Request.Form("Email_Address")) & "', '" & _
Request.ServerVariables("REMOTE_ADDR") & "', " & _
Session.SessionID & ", '" & _
prepareSQL(Request.Form("Address_1")) & "', '" & _
prepareSQL(Request.Form("Address_2")) & "', '" & _
prepareSQL(Request.Form("City")) & "', '" & _
prepareSQL(Request.Form("State")) & "', '" & _
prepareSQL(Request.Form("Zip")) & "', '" & _
prepareSQL(Request.Form("Country")) & "', '" & _
prepareSQL(Request.Form("Phone")) & "', '" & _
prepareSQL(Request.Form("Phone_Extension")) & "', '" & _
prepareSQL(Request.Form("Fax")) & "', '" & _
prepareSQL(Request.Form("Company")) & "', '" & _
prepareSQL(Request.Form("Pay_To")) & "', '" & _
prepareSQL(Request.Form("Tax_ID")) & "', '" & _
prepareSQL(Request.Form("Tax_ID_Type")) & "', '" & _
prepareSQL(Request.Form("Tax_Class")) & "', " & _
Affiliate_ID & "," & _
Request.Form("ID") & "," & _
Request.Form("Approved")
Set objConnection = openConnectionAdmin()
Set objRecordset = openRecordset(strSQL, objConnection)
If objRecordset("Error") = "1" Then
Response.Write objRecordset("Data")
Response.End
End If
objRecordset.Close
Set objRecordset = Nothing
Set objConnection = Nothing
Response.Redirect ( "/admin/users/affiliates/" ) %>
Function openRecordSet(ByVal strSQL, ByRef objConnection)
On Error Resume Next
' logSQL(strSQL)
Set openRecordset = objConnection.Execute(strSQL)
If err.Number <> 0 Then
'Response.Write Err.Number & " - " & Err.Description logError("ASP: openRecordset: " & Err.Number & " - " & Err.Description & ": " & strSQL)
' Call displayErrorPage()
End If
End Function
The error typically is caused by using Set to indicate assignment of an object to a variable, but having a non-object for the right value:
>> Set v = New RegExp
>> [no news here are good news]
>> Set v = "a"
>>
Error Number: 424
Error Description: Object required
So check your openRecordset function. Does it return a recordset by executing
Set openRecordset = ....
(mark the Set) for the given parameters?
Update wrt comments:
This test script:
Option Explicit
' How to test the type of a function's return value that should
' be an object but sometimes isn't. You can't assign the return value
' to a variable because of VBScript's disgusting "Set".
WScript.Echo "TypeName(openConnectionAdmin()): ", TypeName(openConnectionAdmin())
WScript.Echo "TypeName(openRecordset(...)) : ", TypeName(openRecordset("", objConnection))
' Trying to create a connection and a recordset
Dim objConnection : Set objConnection = openConnectionAdmin()
Dim objRecordset : Set objRecordset = openRecordset("", objConnection)
Function openConnectionAdmin()
' Set openConnectionAdmin = CreateObject("ADODB.CONNECTION")
Set openConnectionAdmin = Nothing
End Function
' After removing the comments: Obviously this is a function that
' hides all errors; the programmer should be fed to the lions.
Function openRecordSet(ByVal strSQL, ByRef objConnection)
On Error Resume Next
Set openRecordset = objConnection.Execute(strSQL)
End Function
output:
TypeName(openConnectionAdmin()): Connection
TypeName(openRecordset(...)) : Empty
... Microsoft VBScript runtime error: Object required: 'openRecordset(...)'
or
TypeName(openConnectionAdmin()): Nothing
TypeName(openRecordset(...)) : Empty
... Microsoft VBScript runtime error: Object required: 'openRecordset(...)'
shows: By hiding every conceivable error in openRecordset() the function can return Empty (undetected!), which isn't an object and can't be assigned to a variable by using Set.

Runtime error 3704

In my vb6 I am getting error 3704 operation is not allowed when object is closed.
I have search stackoverflow for similar problem but I think I'm missing something. I need to update every row in vfp based from recordset rs1 Here my code:
Option Explicit
Dim cn As New ADODB.Connection
Dim cn1 As New ADODB.Connection
Private Sub trns_Click()
Set cn = New ADODB.Connection
Set cn1 = New ADODB.Connection
cn.ConnectionString = MDI1.txtcn.Text
cn.Open
cn1.ConnectionString = "Provider=VFPOLEDB;Data Source=\\host1\software\MIL\company0"
cn1.Open
rs1.Open "Select * from trans", cn, adOpenStatic, adLockPessimistic
Do While Not rs2.EOF
rs2.Open "update transac set no_ot_1_5 = " & rs1.Fields("ovt1") & ", no_ot_2_0 = " & rs1.Fields("ovt2") & ", no_ot_3_0" _
& "= " & rs1.Fields("ovt3") & ",Meal_allw = " & rs1.Fields("meal_allow") & ",on_duty = " & rs1.Fields("cnt") & ",no_d_local = " & rs1.Fields("local") & ",no_d_sick" _
& "= " & rs1.Fields("sick") & ",no_d_abs = " & rs1.Fields("absence") & ",no_d_spc = " & rs1.Fields("special") & ",Revenue02" _
& "= " & rs1.Fields("refund") & ",Revenue05 = " & rs1.Fields("prepay") & ",Deduct05 = " & rs1.Fields("prepay") & ",Revenue01 = " & rs1.Fields("comm") & "where code = '" & rs1.Fields("emp_code") & "' and transac.date = CTOD('" & trans.txtend2 & "')", cn1, adOpenDynamic, adLockPessimistic
If Not rs2.EOF Then
rs2.MoveNext
End If
Loop
rs2.close
Update query doesn't return recordset, hence your rs2 is not opened.
You perform your loop on the wrong recordeset : I replaced the some of the rs2 with rs1 in your code.
Do While Not rs1.EOF
rs2.Open "update transac set no_ot_1_5 = " & rs1.Fields("ovt1") & ", no_ot_2_0 = " & rs1.Fields("ovt2") & ", no_ot_3_0" _
& "= " & rs1.Fields("ovt3") & ",Meal_allw = " & rs1.Fields("meal_allow") & ",on_duty = " & rs1.Fields("cnt") & ",no_d_local = " & rs1.Fields("local") & ",no_d_sick" _
& "= " & rs1.Fields("sick") & ",no_d_abs = " & rs1.Fields("absence") & ",no_d_spc = " & rs1.Fields("special") & ",Revenue02" _
& "= " & rs1.Fields("refund") & ",Revenue05 = " & rs1.Fields("prepay") & ",Deduct05 = " & rs1.Fields("prepay") & ",Revenue01 = " & rs1.Fields("comm") & "where code = '" & rs1.Fields("emp_code") & "' and transac.date = CTOD('" & trans.txtend2 & "')", cn1, adOpenDynamic, adLockPessimistic
If Not rs1.EOF Then
rs1.MoveNext
End If
Loop
rs1.close
You dont need to create a recordset to execute an update, insert or delete on the database. Just use the statement cn1.Execute YourSqlStatement where YourSqlStatement is the string you are passing on the rs2.Open instruction. The Execute method on the connection optionally accepts a byRef variable where you can get the number of records affected.
Example:
Dim nRecords As Integer
cn1.Execute "Update Table Set Field = Value Where AnotherField = SomeValue ", nRecords
MsgBox "Total Updated Records: " & Format(nRecords,"0")
try to open your rs2 before using if in the do while statement., or do it like this
rs2.open " blah blah blah "
Do Until rs2.eof
For Each fld In rs2.field
value_holder = fld.value
Next
rs2.movenext
Loop

Resources