getting error "Subscript out of range error" in asp classic - vbscript

I am writing code for string search in classic asp but it show error.
For example if is write in search
my name is lucky from earth
I get this error
Microsoft VBScript runtime error '800a0009'
Subscript out of range: '6'
/bdn6/prod_search.asp, line 68
where line 68 is :
SWord = SWord & " " & Trim(arrKeyWords(j))
my code is as below given:
<%
Dim SearchWord, arrKeyWords, arrQry, MainQty, FinalQty, MergeQry, WhereCon, Cnt, tsearch, i, j
SearchWord = trim(request("searcha"))
arrKeyWords = Split(SearchWord ," ")
Cnt = Ubound(arrKeyWords) + 1
%>
<%
dim Qry, SWord, NLWord, TableName, LastIndex
MainQty = "select a.rProd_name, r_id "
TableName = "from reseller_prod a, brand e, V_brand f, V_modal g Where a.rprod_vbrand=f.Vb_Id and f.vb_active=0 and a.rprod_vmodel=g.Vm_id and g.Vm_active=0 and a.rProd_brand=e.Brand_id and e.brand_active=0 and a.rProd_price <> 0 and a.rProd_price is not Null and a.rprod_nowallowd=0 and a.r_id in(select s_usrid from Reseller where S_approval=0) and a.r_id in(select usr_id from usr where Usr_Active=0)"
NLWord = ""
For i = 0 To Cnt
SWord = ""
For j = 0 To ((Cnt) - i)
SWord = SWord & " " & Trim(arrKeyWords(j)) 'getting error on this line: Subscript out of range
Next
WhereCon = WhereCon & " And (a.rProd_name like '%" & Trim(SWord) & "%' or f.vb_name like '%" & Trim(SWord) & "%' or g.Vm_modal like '%" & Trim(SWord) & "%')"
Qry = MainQty & ", " & (i + 1) & " as SortRecord " & TableName & " " & WhereCon
LastIndex = i + 1
Qry = Qry & NLWord
NLWord = NLWord & " And (a.rProd_name not like '%" & Trim(SWord) & "%' And f.vb_name not like '%" & Trim(SWord) & "%' And g.Vm_modal not like '%" & Trim(SWord) & "%')"
FinalQty = FinalQty & Qry & " UNION "
WhereCon = ""
Qry = ""
Next
FinalQty = left(FinalQty, (Len(FinalQty) - 6))
MergeQry = FinalQty
FinalQty = ""
MainQty = "select a.Prod_name, '' as r_id "
TableName = "from product a, brand e, V_brand f, V_modal g Where a.prod_vbrand=f.Vb_Id and f.vb_active=0 and a.prod_vmodel=g.Vm_id and g.Vm_active=0 and a.Prod_brand=e.Brand_id and e.brand_active=0 and a.prod_active=0 and a.Prod_price <> 0 and a.Prod_price is not Null"
NLWord = ""
For i = 0 To Cnt
SWord = ""
For j = 0 To ((Cnt) - i)
SWord = SWord & " " & Trim(arrKeyWords(j))
Next
WhereCon = WhereCon & " And (a.Prod_name like '%" & Trim(SWord) & "%' or a.prod_keyword like '%" & Trim(SWord) & "%' or f.vb_name like '%" & Trim(SWord) & "%' or g.Vm_modal like '%" & Trim(SWord) & "%')"
Qry = MainQty & ", " & (LastIndex + i + 1) & " as SortRecord " & TableName & " " & WhereCon
Qry = Qry & NLWord
NLWord = NLWord & " And (a.Prod_name not like '%" & Trim(SWord) & "%' and a.prod_keyword not like '%" & Trim(SWord) & "%' And f.vb_name not like '%" & Trim(SWord) & "%' And g.Vm_modal not like '%" & Trim(SWord) & "%')"
FinalQty = FinalQty & Qry & " UNION "
WhereCon = ""
Qry = ""
Next
FinalQty = left(FinalQty, (Len(FinalQty) - 6))
FinalQty = FinalQty & "Order By SortRecord"
MergeQry = MergeQry & " UNION " & FinalQty
response.Write(MergeQry)
%>
Please help me to resolve this issue.

Read something about Array Variables:
Dim A(10)
Although the number shown in the parentheses is 10, all arrays in
VBScript are zero-based, so this array actually contains 11
elements. In a zero-based array, the number of array elements is
always the number shown in parentheses plus one. This kind of array is
called a fixed-size array.
Split Function
Returns a zero-based, one-dimensional array containing a specified
number of substrings.
UBound Function
Returns the largest available subscript for the indicated dimension of
an array.
Therefore, use either
Cnt = Ubound(arrKeyWords) ''' instead of Cnt = Ubound(arrKeyWords) + 1
or (insisting upon Cnt = Ubound(arrKeyWords) + 1)
For i = 0 To Ubound(arrKeyWords)
SWord = ""
For j = 0 To (Ubound(arrKeyWords) - i)
SWord = SWord & " " & Trim(arrKeyWords(j))
Next
''' … '''
Next
or (insisting upon Cnt = Ubound(arrKeyWords) + 1)
For i = 0 To cnt -1
SWord = ""
For j = 0 To (cnt - 1 - i)
SWord = SWord & " " & Trim(arrKeyWords(j))
Next
''' … '''
Next

Related

Scheduling Conflict: can only detect conflict with exact time

This is the last problem I have to face in for my capstone project, and it's driving me nuts.
Basically, I have to be able to identify if Section/Faculty/Room are all in use when scheduling a subject, to avoid conflicts.
Here's what I've worked on, but so far it can only detect when Room is in use.
I can't figure out how to be able to prevent scheduling that's in-between time periods. For example: First entry would be 7-8:30AM. Second entry would be 7:30 AM to 9 AM. With the former existing, it should reject the latter but I can't figure out how to do that. This is what I've cooked up so far. How would you guys go about this?
Public Function DataInUse() As Boolean
Dim Temp As Boolean
Temp = False
If FacultyInUse() = True Then
MessageBox.Show("Faculty in use.")
cboFaculty.Focus()
DisplayFacultyInUse()
DisplayLabelConflictForFaculty()
Temp = True
ElseIf RoomInUse() = True Then
MessageBox.Show("Room in use.")
cboRoom.Focus()
DisplayRoomInUse()
DisplayLabelConflictForRoom()
Temp = True
End If
Return Temp
End Function
Public Function FacultyInUse() As Boolean
Dim com As New OleDbCommand(" Select * from qrySubjectOfferring Where cTimeIn >=#" & cboFrom.Text & "# and cTimeOut <=#" & cboTo.Text & "# and Faculty like'" & cboFaculty.Text & "%' and cDay Like '%" & cboDay.Text & "%'", clsCon.con)
Dim dr As OleDbDataReader = com.ExecuteReader()
dr.Read()
If dr.HasRows Then
Return True
Else
Return False
End If
End Function
Public Function RoomInUse() As Boolean
Dim com As New OleDbCommand("Select * from qryRoomAvailability WHERE (cTimeIn <=#" & cboFrom.Text & "# AND cTimeOut >=#" & cboFrom.Text & "# AND Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "') OR (cTimeIn <=#" & cboTo.Text & "# AND cTimeOut >=#" & cboTo.Text & "# AND Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "') OR (cTimeIn >= #" & cboFrom.Text & "# AND cTimeOut <= #" & cboTo.Text & "# AND Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "') ", clsCon.con)
Dim dr As OleDbDataReader = com.ExecuteReader()
dr.Read()
If dr.HasRows Then
Return True
Else
Return False
End If
End Function
Public Function SubjectAlreadyOffered(sSubject As String) As Boolean
Dim com As New OleDbCommand("Select * from qrySubjectOfferring Where Subject LIKE '%" & sSubject & "%'", clsCon.con)
Dim dr As OleDbDataReader = com.ExecuteReader()
dr.Read()
If dr.HasRows Then
Return True
Else
Return False
End If
End Function
Try simplifying your SQL to use Between clause and eliminate all entries where the From or To are in existing entries
In your RoomInUse() function
Dim strSQL as String
strSQL = "SELECT * FROM qryRoomAvailability WHERE " & _
" Room = '" & cboRoom.Text & "' AND cDay = '" & cboDay.Text & "'" & _
" AND NOT (#" & cboFrom.Text "# BETWEEN [" & cTimeIn & "] AND [" & cTimeOut & "])" & _
" AND NOT (#" & cboTo.Text "# BETWEEN [" & cTimeIn & "] AND [" & cTimeOut & "])"
Dim com As New OleDbCommand(strSQL, clsCon.con)

I am getting error Microsoft VBScript runtime error '800a0009' Subscript out of range: 'j'

I am trying to insert data in classic asp but getting following error:
Microsoft VBScript runtime error '800a0009' Subscript out of range: 'j'
For reference I am attaching my code. I am new to classic asp
IF Len(FixString(Request.Form("txtModelTypeID"))) >= 1 AND cboSlab = "SlabCombineSeries" Then
arrModelTypeID = split(trim(Request.Form("txtModelTypeID")),",")
arrModelID = split(trim(Request.Form("txtModelID")),",")
arrSlab = split(trim(Request.Form("txtSlab")),",")
arrAmount = split(trim(Request.Form("txtAmount")),",")
arrSF = split(trim(Request.Form("txtSF")),",")
arrNonSF = split(trim(Request.Form("txtNonSF")),",")
arrPMY = split(trim(Request.Form("txtPMY")),",")
arrCMY = split(trim(Request.Form("txtCMY")),",")
arrPIY = split(trim(Request.Form("txtPIY")),",")
arrCIY = split(trim(Request.Form("txtCIY")),",")
arrTradeIn = split(trim(Request.Form("txtTradeIn")),",")
arrLoyalty = split(trim(Request.Form("txtLoyalty")),",")
arrSpecial1 = split(trim(Request.Form("txtSpecial1")),",")
arrSpecial2 = split(trim(Request.Form("txtSpecial2")),",")
arrSpecial3 = split(trim(Request.Form("txtSpecial3")),",")
arrkeydiscount = split(trim(Request.Form("txtkeydiscount")),",")
arrsme = split(trim(Request.Form("txtsme")),",")
if ubound(arrModelTypeID) = 0 Then
elseif ubound(arrModelTypeID) > 0 Then
FOR j = 0 to ubound(arrModelTypeID)
if NOT ISNumeric(TRIM(arrSlab(j))) Then Slab = 0 else Slab = TRIM(arrSlab(j)) end if
if NOT ISNumeric(TRIM(arrAmount(j))) Then Amount = 0 else Amount = TRIM(arrAmount(j)) end if
if NOT ISNumeric(TRIM(arrSF(j))) Then SF = 0 else SF = TRIM(arrSF(j)) end if
if NOT ISNumeric(TRIM(arrNonSF(j))) Then NonSF = 0 else NonSF = TRIM(arrNonSF(j)) end if
if NOT ISNumeric(TRIM(arrPMY(j))) Then PMY = 0 else PMY = TRIM(arrPMY(j)) end if
if NOT ISNumeric(TRIM(arrCMY(j))) Then CMY = 0 else CMY = TRIM(arrCMY(j)) end if
if NOT ISNumeric(TRIM(arrPIY(j))) Then PIY = 0 else PIY = TRIM(arrPIY(j)) end if
if NOT ISNumeric(TRIM(arrCIY(j))) Then CIY = 0 else CIY = TRIM(arrCIY(j)) end if
if NOT ISNumeric(TRIM(arrTradeIn(j))) Then TradeIn = 0 else TradeIn = TRIM(arrTradeIn(j)) end if
if NOT ISNumeric(TRIM(arrLoyalty(j))) Then Loyalty = 0 else Loyalty = TRIM(arrLoyalty(j)) end if
if NOT ISNumeric(TRIM(arrSpecial1(j))) Then Special1 = 0 else Special1 = TRIM(arrSpecial1(j)) end if
if NOT ISNumeric(TRIM(arrSpecial2(j))) Then Special2 = 0 else Special2 = TRIM(arrSpecial2(j)) end if
if NOT ISNumeric(TRIM(arrSpecial3(j))) Then Special3 = 0 else Special3 = TRIM(arrSpecial3(j)) end if
if NOT ISNumeric(TRIM(arrkeydiscount (j))) Then Key = 0 else Key = TRIM(arrkeydiscount(j)) end if
if NOT ISNumeric(TRIM(arrsme (j))) Then Sme = 0 else Sme = TRIM(arrsme(j)) end if
SQL = SQL & "INSERT INTO demo_Item ( " &_
" iSPCMasterID, iModelID, vModelName, vModelCode, iSlab, mAmount, " &_
" mSF, mNonSF, mPMY, mCMY, mPIY, mCIY, mTradeIn, mLoyalty, " &_
" mSpecial1, mSpecial2,key_acc,sme, mSpecial3, dCreateDate, iSeq) " &_
" SELECT #NewID, i_modelid, vch_modelname, modelcode, " &_
" " & Slab & ", " &_
" " & Amount & ", " &_
" " & SF & ", " &_
" " & NonSF & ", " &_
" " & PMY & ", " &_
" " & CMY & ", " &_
" " & PIY & ", " &_
" " & CIY & ", " &_
" " & TradeIn & ", " &_
" " & Loyalty & ", " &_
" " & Special1 & ", " &_
" " & Special2 & ", " &_
" " & Key & ", " &_
" " & Sme & ", " &_
" " & Special3 & " , getdate(), " & j + 1 &_
" FROM ltr_or_models WHERE CAST(i_modeltypeid as varchar(20)) = '" & trim(arrModelTypeID(j)) & "' "
next
end if
You are attempting to loop through multiple arrays simultaneously using a single counter. I.E. You are setting the end of the j counter using the upper level of the arrModelTypeID array and then expecting the remaining and separate arrays (arrSlab, arrAmount etc.) to use the same counter.
Assuming the data in all your newly created arrays are ordered identically to each other. Try checking each array record for a value before setting its assigned variable.
E.G. CHANGE
if NOT ISNumeric(TRIM(arrSlab(j))) Then Slab = 0 else Slab = TRIM(arrSlab(j)) end if
TO
If arrSlab(j) <> "" Then
if NOT ISNumeric(TRIM(arrSlab(j))) Then Slab = 0 else Slab = TRIM(arrSlab(j)) end if
End If

VBScript output as Excel worksheet not working

I've got a page that will either display information in an HTML table or output that same info as an excel file.
The HTML view is working fine, but the excel portion fails with : (500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed.)
Ideally, if its possible to separate the excel portion of the code I'd rather have that as the final product, but I need to get it working first. I'd appreciate any ideas.
<%# Language=VBScript %>
<% Session("CurrentPageTitle") = "Test Transaction Summary" %>
<%
Response.Buffer = TRUE
if Request.Form("present") = "xls" then
set objXL = CreateObject("Excel.Application")
Set objWB = objXL.WorkBooks.Open("C:\Inetpub\wwwroot\temp\xl.xlsx")
Set objWS = objXL.ActiveWorkBook.WorkSheets("Sheet1")
numRow = 9
end if
if Request.Form("present") <> "xls" then
%>
<!--#include file="../common/header.inc"-->
<%
end if
varState = Request.QueryString("state")
varCustomerIdentifier = Request.Form("Customer")
CustomerArray = Split(varCustomerIdentifier,",")
varCustomer = CustomerArray(0)
varSub = CustomerArray(1)
varCity = CustomerArray(2)
if Request.Form("Summary") = "user" and varState <> "u" then
'Should not be here, form navigation glitch - go to GetUserParam.asp
location.href="GetUserParam.asp?f=" & varCustomerIdentifier & "&t=user"
else
if varState = "u" then
varYesterday = Request.Form("Smonth") + "/" + Request.Form("Sday")+ "/" + Request.Form("Syear")
varToday = Request.Form("Emonth") + "/" + Request.Form("Eday")+ "/" + Request.Form("Eyear")
elseif varState = "m" then
varYesterday = month(date()) & "/1/" & year(date())
varToday = date()
strYesterday = dateadd("d",-1,date())
elseif varState = "y" then
varYesterday = "1/1/" & year(date())
varToday = date()
strYesterday = dateadd("d",-1,date())
elseif varState = "s" then
varYesterday = Request.Form("Smonth") + "/" + Request.Form("Sday")+ "/" + Request.Form("Syear")
varToday = Request.Form("Emonth") + "/" + Request.Form("Eday")+ "/" + Request.Form("Eyear")
varInterval = Request.Form("Interval")
else
varYesterday = cdate(datepart("m",date()-1) & "/" & datepart("d",date()-1) & "/" & datepart("yyyy",date()-1))
varToday = cdate(datepart("m",date()) & "/" & datepart("d",date()) & "/" & datepart("yyyy",date()))
end if
if varCustomer = "0" then
strSQL = "select CustomerNo, SubNo, City, CustomerName from Customer order by CustomerName"
else
strSQL = "select CustomerNo, SubNo, City, CustomerName from Customer where CustomerNo = " & varCustomer & " and SubNo = " & varSub & " and City = " & varCity & " order by CustomerName"
end if
' sjs
dim DBCONN
set DBCONN = Server.CreateObject("ADODB.Connection")
DBCONN.CommandTimeout = 60000
DBCONN.ConnectionTimeout = 60000
DBCONN.Open "DSN=***;UID=***;PWD=***;"
set DBConnection = DBCONN
set DBQuery = Server.CreateObject("ADODB.Command")
DBQuery.ActiveConnection = DBConnection
DBQuery.CommandType = 1
DBQuery.CommandText = strSQL
DBQuery.CommandTimeout = 900
Err.Clear
set dbRS = DBQuery.Execute
AllUpdateCount = 0
AllInquiryCount = 0
AllMTCount = 0
AllETCount = 0
AllTotalCount = 0
index = 0
while not dbRS.EOF
index = index + 1
if Request.Form("Summary") = "prevd" then
strType = "Yesterday"
strNote = "(from " & varYesterday & ")"
strFormatSQL = "select distinct [Format] 'formatid' from TransactionSummary where CustomerNo = " & dbRS.Fields("CustomerNo").Value & " and SubNo = " & dbRS.Fields("SubNo").Value & " and City = " & dbRS.Fields("City").Value & " and TransactionDate = '" & varYesterday & "'"
elseif Request.Form("Summary") = "user" then
strType = "User Specified"
strFormatSQL = "select distinct [Format] 'formatid' from TransactionSummary where CustomerNo = " & dbRS.Fields("CustomerNo").Value & " and SubNo = " & dbRS.Fields("SubNo").Value & " and City = " & dbRS.Fields("City").Value & " and TransactionDate >= '" & varYesterday & "' and TransactionDate <= '" & varToday & "'"
strNote = "(from " & varYesterday & " to " & varToday & ")"
elseif Request.Form("Summary") = "mtd" then
strType = "Month To Date"
strFormatSQL = "select distinct [Format] 'formatid' from TransactionSummary where CustomerNo = " & dbRS.Fields("CustomerNo").Value & " and SubNo = " & dbRS.Fields("SubNo").Value & " and City = " & dbRS.Fields("City").Value & " and TransactionDate >= '" & varYesterday & "' and TransactionDate < '" & varToday & "'"
strNote = "(from " & varYesterday & " through " & varToday & ")"
elseif Request.Form("Summary") = "ytd" then
strType = "Year To Date"
strFormatSQL = "select distinct [Format] 'formatid' from TransactionSummary where CustomerNo = " & dbRS.Fields("CustomerNo").Value & " and SubNo = " & dbRS.Fields("SubNo").Value & " and City = " & dbRS.Fields("City").Value & " and TransactionDate >= '" & varYesterday & "' and TransactionDate < '" & varToday & "'"
strNote = "(from " & varYesterday & " through " & varToday & ")"
elseif Request.Form("Summary") = "stats" then
strType = "Usage Statistics"
strFormatSQL = "select TransactionDate from TransactionDetail where CustomerNo = " & dbRS.Fields("CustomerNo").Value & " and SubNo = " & dbRS.Fields("SubNo").Value & " and City = " & dbRS.Fields("City").Value & " and TransactionDate >= '" & varYesterday & "' and TransactionDate <= '" & varToday & " 11:59:59 PM'"
strNote = "(from " & varYesterday & " to " & varToday & ")"
else
strFormatSQL = ""
end if
'very top
if Request.Form("present") = "xls" then
if varCustomer = "0" and index = 1 then
objXL.Cells(5,2) = strType & " Summary For ALL Customers"
objXL.Cells(6,2) = strNote
end if
if varCustomer ="0" then
else
objXL.Cells(5,2) = strType & " Summary For Customer: " & Trim(dbRS.Fields("CustomerName").Value) & " - City " & Trim(dbRS.Fields("City").Value)
objXL.Cells(6,2) = strNote
end if
elseif Request.Form("present") <> "xls" then
if varCustomer = "0" and index = 1 then
Response.Write("<h3>" & strType & " Summary for All Customers<br>" & chr(13))
Response.Write("<font size=""-1"">" & strNote & "</font></h3>" & chr(13))
Response.Write("<table border=""1"" id=""exCity"" runat=""server"">" & chr(13))
Response.Write("<tr>" & chr(13))
Response.Write("<td align=""center""><strong>Customer</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>City</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>Inquiry</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>Update</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>Total</strong></td>" & chr(13))
Response.Write("</tr>" & chr(13))
end if
' Customer and City for ALL Customers added above each record top
if varCustomer = "0" then
' Response.Write("<h3><i>" & Trim(dbRS.Fields("CustomerName").Value) & " - Po------------rt " & Trim(dbRS.Fields("City").Value) & "</i></h3>" & chr(13))
'Customer and City for a single Customer added to very top
else
Response.Write("<h3>" & strType & " Summary for Customer: " & Trim(dbRS.Fields("CustomerName").Value) & " - City " & Trim(dbRS.Fields("City").Value) & "<br>" & chr(13))
Response.Write("<font size=""-1"">" & strNote & "</font></h3>" & chr(13))
'start a table with format request name transatctions at the top
Response.Write("<table border=""1"" id=""exCity"" runat=""server"">" & chr(13))
Response.Write("<tr>" & chr(13))
Response.Write("<td align=""center""><strong>Customer</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>City</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>Inquiry</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>Update</strong></td>" & chr(13))
Response.Write("<td align=""center""><strong>Total</strong></td>" & chr(13))
Response.Write("</tr>" & chr(13))
end if
end if
'query db for one Customer
DBQuery.CommandText = strFormatSQL
Err.Clear
set dbRS3 = DBQuery.Execute
UpdateTotalCount = 0
InquiryTotalCount = 0
MTTotalCount = 0
ETTotalCount = 0
CustomerTotalCount = 0
IntervalCounter = 0
IntervalStart = varYesterday & " 12:00:00 AM"
while not dbRS3.EOF
if varState = "s" then
Difference = datediff("n", IntervalStart, dbRS3.Fields("TransactionDate").Value)
if (CInt(Difference) < CInt(varInterval)) then
IntervalCounter = IntervalCounter + 1
else
IntervalNext = dateadd("n", varInterval, IntervalStart)
Response.Write("<tr><td align=""left"">" & IntervalStart & " to <br>" & IntervalNext & "</td><td align=""center"" valign=""middle"">" & IntervalCounter & "</td></tr>" & chr(13))
IntervalCounter = 0
IntervalStart = IntervalNext
end if
else
if Request.Form("Summary") = "prevd" then
strSQL = "select Sum(s.TransactionCount) 'hits', r.RequestName from TransactionSummary as s LEFT JOIN RepositoryDB.dbo.BLS_REQ as r ON s.[Format] = r.RequestID where s.CustomerNo = " & dbRS.Fields("CustomerNo").Value & " and s.SubNo = " & dbRS.Fields("SubNo").Value & " and s.City = " & dbRS.Fields("City").Value & " and s.TransactionDate = '" & varYesterday & "' and s.[Format] = " & dbRS3.Fields("formatid").Value & " GROUP BY r.RequestName"
else
strSQL = "select sum(s.TransactionCount) 'hits', r.RequestName from TransactionSummary as s LEFT JOIN RepositoryDB.dbo.BLS_REQ as r ON s.[Format] = r.RequestID where s.CustomerNo = " & dbRS.Fields("CustomerNo").Value & " and s.SubNo = " & dbRS.Fields("SubNo").Value & " and s.City = " & dbRS.Fields("City").Value & " and s.TransactionDate >= '" & varYesterday & "' and s.TransactionDate <= '" & varToday & "' and s.[Format] = " & dbRS3.Fields("formatid").Value & " GROUP BY r.RequestName"
end if
DBQuery.CommandText = strSQL
Err.Clear
set dbRS2 = DBQuery.Execute
If Err.Number <> 0 Then
Response.Write("Could not get Transaction Summary - database error. SQL Script = " & strSQL)
End If
' Count the hits into their respective total
If (Trim(dbRS3.Fields("formatid").Value) = 25) or (Trim(dbRS3.Fields("formatid").Value) = 425 )Then
MTTotalCount = MTTotalCount + dbRS2.Fields("hits").value
ElseIf (Trim(dbRS3.Fields("formatid").Value = 23)) Then
ETTotalCount = ETTotalCount + dbRS2.Fields("hits").value
ElseIf (Trim(dbRS3.Fields("formatid").Value) = 38) or _
((Trim(dbRS3.Fields("formatid").Value) >= 400) and _
(Trim(dbRS3.Fields("formatid").Value) <= 499) or _
((Trim(dbRS3.Fields("formatid").Value) >= 800) and _
(Trim(dbRS3.Fields("formatid").Value) <= 899))) Then
UpdateTotalCount = UpdateTotalCount + dbRS2.Fields("hits").value
Else
InquiryTotalCount = InquiryTotalCount + dbRS2.Fields("hits").value
End If
set dbRS2 = nothing
end if
dbRS3.MoveNext
wend
set dbRS3 = nothing
UpdateTotalCount = UpdateTotalCount + MTTotalCount + ETTotalCount
CustomerTotalCount = UpdateTotalCount + InquiryTotalCount
' show totals
if Request.Form("present") = "xls" then
objXL.Cells(numRow,2) = Trim(dbRS.Fields("CustomerName").Value)
objXL.Cells(numRow,3) = Trim(dbRS.Fields("City").Value)
objXL.Cells(numRow,4) = UpdateTotalCount
objXL.Cells(numRow,5) = InquiryTotalCount
objXL.Cells(numRow,6) = CustomerTotalCount
objXL.Range("B" & numRow & ":F" & numRow).BORDERS.Weight = 2
numRow = numRow + 1
end if
if Request.Form("present") <> "xls" then
if varState <> "s" then
Response.Write("<tr>" & chr(13))
Response.Write("<td align=""left"">" & Trim(dbRS.Fields("CustomerName").Value) & "</td>" & chr(13))
Response.Write("<td align=""center"">" & Trim(dbRS.Fields("City").Value) & "</td>" & chr(13))
Response.Write("<td align=""center"">" & UpdateTotalCount & "</td>" & chr(13))
Response.Write("<td align=""center"">" & InquiryTotalCount & "</td>" & chr(13))
Response.Write("<td align=""center"">" & CustomerTotalCount & "</td>" & chr(13))
Response.Write("</tr>" & chr(13))
else
IntervalNext = dateadd("n", varInterval, IntervalStart)
Response.Write("<tr><td align=""left"">" & IntervalStart & " to <br>" & IntervalNext & "</td><td align=""center"" valign=""middle"">" & IntervalCounter & "</td></tr>" & chr(13))
end if
' Response.Write("</table>" & chr(13))
end if
'set dbRS2 = nothing
dbRS.MoveNext
AllUpdateCount = AllUpdateCount + UpdateTotalCount
AllInquiryCount = AllInquiryCount + InquiryTotalCount
AllMTCount = AllMTCount + MTTotalCount
AllETCount = AllETCount + ETTotalCount
AllTotalCount = AllTotalCount + CustomerTotalCount
'do grand totals
wend
set dbRS = nothing
if Request.Form("present") <> "xls" then
Response.Write("</table>" & chr(13))
if varCustomer = "0" and varState <> "s" then
Response.Write("<h3>Grand Total Update = " & AllUpdateCount & "</h3>" & chr(13))
Response.Write("<h3>Grand Total Inquiry = " & AllInquiryCount & "</h3>" & chr(13))
Response.Write("<h3>Grand Total for All Customers = " & AllTotalCount & "</h3>" & chr(13))
Response.Write("<h3>Grand Total Manual Transactions = " & AllMTCount & "</h3>" & chr(13))
Response.Write("<h3>Grand Total Early Transactions = " & AllETCount & "</h3>" & chr(13))
end if
end if
end if
if Request.Form("present") <> "xls" then
%><!--#include file="../Common/footer.inc"--><%
end if
if Request.Form("present") = "xls" then
objXL.Cells(numRow+1,4) = "Copyright " & Year(Date)
objXL.Cells(numRow+2,4) = "All Rights Reserved"
Set Fso = CreateObject("Scripting.FileSystemObject")
If (Fso.FileExists("C:\Inetpub\temp\xl2.xlsx")) Then
Set MyFile = Fso.GetFile("C:\Inetpub\temp\xl2.xlsx")
MyFile.Delete
Set MyFile=nothing
End If
Set Fso=nothing
objWB.SaveAs "C:\Inetpub\temp\xl2.xlsx"
objWB.Close
objXL.Quit
Response.Redirect "/temp/xl2.asp"
end if
%>
This section of your code:
if Request.Form("present") = "xls" then
objXL.Cells(numRow,2) = Trim(dbRS.Fields("CustomerName").Value)
objXL.Cells(numRow,3) = Trim(dbRS.Fields("City").Value)
objXL.Cells(numRow,4) = UpdateTotalCount
objXL.Cells(numRow,5) = InquiryTotalCount
objXL.Cells(numRow,6) = CustomerTotalCount
objXL.Range("B" & numRow & ":F" & numRow).BORDERS.Weight = 2
numRow = numRow + 1
end if
Is referring to the Cells and Range objects with the wrong parent object. The parent to these would be the worksheet, which you have previously set as objWS. Also note that you really should set objWS like this:
Set objWS = objWB.Worksheets("Sheet1")
because the ActiveWorkbook can change when you least expect it... :)

VB Script help in writing event logs to excel

I have the below script to fetch the event logs from system and write to an excel. It is running fine on 'Windows 7', but on 'Windows Server 2003', it is taking 7-8 minutes to write the systems logs, and it writes the Application logs within seconds. However there are very few number of errors in the system logs.
Another problem is I am using MyDate = DateAdd("h", -8, Now()) in the script but it fetches logs for more than 12 hours ago. This time calculation is not functioning correctly.
Your help will be highly appreciated.
Here is the script:
Option Explicit
Dim objFSO, objFolder, objFile, objWMI, objItem, objItem1, objItem2 ' Objects
Dim strComputer, strFileName, strFileOpen, strFolder, strPath, oExcel, oWB, oSheet, oSheet1, oSheet2
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents, colLoggedEvents2, colLoggedEvents3, MyDate, dtm, row, row1, row2, Query, ServerTime
MyDate = DateAdd("h", -8, Now())
'---------------------------------------------------------
On Error Resume Next
Set oExcel=CreateObject("Excel.Application")
oExcel.Visible=true
Set oWB=oExcel.Workbooks.Open ("D:\EventLogs2.xls")
Set oSheet=oWB.Worksheets.Add ( , oWB.WorkSheets(oWB.WorkSheets.Count))
Set oSheet1=oWB.Worksheets.Add ( , oWB.WorkSheets(oWB.WorkSheets.Count))
Set oSheet2=oWB.Worksheets.Add ( , oWB.WorkSheets(oWB.WorkSheets.Count))
oSheet.Name="Application"
oSheet1.Name="Security"
oSheet2.Name="System"
strComputer = "."
ServerTime = Now
intRecordNum = 0
row = 0
row1 = 0
row2 = 0
' ----------------------------------------------------------
' WMI Core Section
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Application' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents2 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Security' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents3 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'System' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
' ----------------------------------------------------------
' Next section loops through ID properties
For Each objItem in colLoggedEvents
If objItem.EventType=1 then
row = row+1
osheet.Cells(row,1).Value = ("Logfile: " & objItem.Logfile _
& " source " & objItem.SourceName)
osheet.Cells(row,2).Value = ("Message: " & objItem.Message)
osheet.Cells(row,3).Value = ("TimeGenerated: " & WMIDateStringToDate(objItem.TimeGenerated))
osheet.Cells(row,4).Value = ServerTime
End If
Next
For Each objItem1 in colLoggedEvents2
If objItem1.EventType=1 then
row1 = row1+1
osheet1.Cells(row1,1).Value = ("Logfile: " & objItem1.Logfile _
& " source " & objItem1.SourceName)
osheet1.Cells(row1,2).Value = ("Message: " & objItem1.Message)
osheet1.Cells(row1,3).Value = ("TimeGenerated: " & WMIDateStringToDate(objItem1.TimeGenerated))
osheet1.Cells(row1,4).Value = ServerTime
End If
Next
For Each objItem2 in colLoggedEvents3
If objItem2.EventType=1 then
row2 = row2+1
osheet2.Cells(row2,1).Value = ("Logfile: " & objItem2.Logfile _
& " source " & objItem2.SourceName)
osheet2.Cells(row2,2).Value = ("Message: " & objItem2.Message)
osheet2.Cells(row2,3).Value = ("TimeGenerated: " & WMIDateStringToDate(objItem2.TimeGenerated))
osheet2.Cells(row2,4).Value = ServerTime
intRecordNum = intRecordNum +1
End If
Next
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function
oWB.save
oWB.Application.Quit
WScript.Quit
Can't you just write to a CSV file?
Something like this:
Option Explicit
Dim objFSO, objFolder, objFile, objWMI, objItem, objItem1, objItem2 ' Objects
Dim strComputer, strFileName, strFileOpen, strFolder, strPath, oExcel, oWB, oSheet, oSheet1, oSheet2
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents, colLoggedEvents2, colLoggedEvents3, MyDate, dtm, row, row1, row2, Query, ServerTime
MyDate = DateAdd("h", -8, Now())
'---------------------------------------------------------
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("D:\EventLogs2.csv", True)
strComputer = "."
ServerTime = Now
intRecordNum = 0
row = 0
row1 = 0
row2 = 0
' ----------------------------------------------------------
' WMI Core Section
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Application' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents2 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'Security' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
Set colLoggedEvents3 = objWMI.ExecQuery _
("SELECT * FROM Win32_NTLogEvent where Logfile = 'System' and " _
& "EventType = '1' and TimeWritten > '" & MyDate & "'")
' ----------------------------------------------------------
' Next section loops through ID properties
For Each objItem in colLoggedEvents
If objItem.EventType=1 then
objFile.WriteLine("Logfile: " & objItem.Logfile & "," & " source " & objItem.SourceName & "," & _
"Message: " & objItem.Message & "," & _
"TimeGenerated: " & WMIDateStringToDate(objItem.TimeGenerated) & "," & _
ServerTime)
End If
Next
For Each objItem1 in colLoggedEvents2
If objItem1.EventType=1 then
objFile.WriteLine("Logfile: " & objItem1.Logfile & "," & " source " & objItem1.SourceName & "," & _
"Message: " & objItem1.Message & "," & _
"TimeGenerated: " & WMIDateStringToDate(objItem1.TimeGenerated) & "," & _
ServerTime)
End If
Next
For Each objItem2 in colLoggedEvents3
If objItem2.EventType=1 then
objFile.WriteLine("Logfile: " & objItem2.Logfile & "," & " source " & objItem2.SourceName & "," & _
"Message: " & objItem2.Message & "," & _
"TimeGenerated: " & WMIDateStringToDate(objItem2.TimeGenerated) & "," & _
ServerTime)
End If
Next
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
End Function
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing

IndexOutOfRangeException when passing empty string array to WebMethod

Tried every combo I can think of: String.Empty, IsDBNull.
selectPONumber is passed to "ByVal selectPONumber() As String" from "selectPONumber: [' + JSON.stringify('') + ']"
The StackTrace point to the second line of this VB
VB
If Not IsDBNull(selectPONumber) Then
If selectPONumber.Length > 1 Then
qry = qry + "and ("
For u As Integer = 0 To selectPONumber.Length - 1
If u <> selectPONumber.Length Then
qry = qry + "and B.PONumber = '" & selectPONumber(u) & "' or "
Else
qry = qry + "and B.PONumber = '" & selectPONumber(u) & "'"
End If
Next
qry = qry + ") "
Else
qry = qry + "and B.PONumber = '" & selectPONumber(0) & "' "
End If
End If
Many thanks in advance!
Update
Replaced all lengths with counts, and took tranceporter's advice. Now, it gives the same error on the "for" line. How did it make it past the If selectPONumber.Length > 1 ?
Updated Code
If selectPONumber IsNot Nothing AndAlso selectPONumber.Count > 1 Then
qry = qry + "and ("
For u As Integer = 0 To (selectPONumber.Count - 1)
If u <> selectPONumber.Count Then
qry = qry + "B.PONumber = '" & selectPONumber(u) & "' or "
Else
qry = qry + "B.PONumber = '" & selectPONumber(u) & "'"
End If
Next
qry = qry + ") "
ElseIf selectPONumber(0) <> "" Then
qry = qry + "and B.PONumber = '" & selectPONumber(0) & "' "
End If
Solution
tranceporter's solution is correct. I stupidly treated a regular string as an array elsewhere in my code. It started pointing all over the rest of the function as indexoutofbounds.
try using this (unless you already have)
If selectPONumber IsNot Nothing Then
If selectPONumber.Count > 0 Then
qry = qry + "and ("
For u As Integer = 0 To selectPONumber.Count - 1
If u <> selectPONumber.Count Then
qry = qry + "B.PONumber = '" & selectPONumber(u) & "' or "
Else
qry = qry + "B.PONumber = '" & selectPONumber(u) & "'"
End If
Next
qry = qry + ") "
Else
qry = qry + "and B.PONumber = '" & selectPONumber(0) & "' "
End If
End If

Resources