Loop throught a description, find a string and count - vbscript

I have a table with, for this example, 2 columns:
Person
Description
I need to create a result table like this:
Person Yes No Total
John 1 5 6
Laura 4 9 13
Peter 0 1 1
Total 5 15 20
The person I get it straight, but for the description I have to do a check if there is a date inside the string, Nathan Rice helped me here about it: Get a range date and search a string. One Person can have N descriptions, so I need to loop it. If the date was found in description add 1 to Yes, else add 1 to No.
CODE UPDATED
<%
varYesTotal = 0
varNoTotal = 0
Do While Not rsPerson.EOF
varYes = 0
varNo = 0
strPersonName = rsPerson("Person")
Set rsCheckYesNo = T.Execute("SELECT Description FROM Person Where Person= '" & strPersonName & "' ORDER BY Person ASC")
strDescription= rsCheckYesNo("Description")
For intDateDiff = 0 to DateDiff("d",DataInicial,DataFinal)
arrDateParts = Split(DateAdd("d",intDateDiff,DataInicial),"/")
If arrDateParts(1) <= 9 Then
arrDateParts(1) = "0" & arrDateParts(1)
End If
strCheckDate = arrDateParts(0) & "/" & arrDateParts(1) & "/" & arrDateParts(2)
Do While Not rsCheckYesNo.EOF
strDescription= rsCheckYesNo("Description")
boolDateFound = False
If InStr(strDescription, strCheckDate) > 0 Then
boolDateFound = True
varYes = varYes + 1
Else
varNo = varNo + 1
End If
rsCheckYesNo.MoveNext
Loop
Next
%>

<%
Set rsPerson= T.Execute("SELECT DISTINCT Person FROM Table")
If Not rsPerson.EOF Then
%>
<table>
<thead>
<tr>
<th>Person</th>
<th>Yes</th>
<th>No</th>
<th>Total</th>
</tr>
</thead>
<%
'We need 2 sets of counters, one set that gets set
'to zero so we can total all the records.
varYesTotal = 0
varNoTotal = 0
Do While Not rsPerson.EOF
'The other set of counters gets reset per user
'so it should be inside the users loop.
varYes = 0
varNo = 0
strPersonName = rsPerson("Person")
Set rsCheckYesNo = T.Execute("SELECT Description FROM Person Where Person= '" & strPersonName & "' ORDER BY Person ASC")
strDescription= rsCheckYesNo("Description")
Do While Not rsCheckYesNo.EOF
'Start Nathan Rice Code
boolDateFound = False
For intDateDiff = 0 to DateDiff("d",DataInicial,DataFinal)
arrDateParts = Split(DateAdd("d",intDateDiff,DataInicial),"/")
If arrDateParts(1) <= 9 Then
arrDateParts(1) = "0" & arrDateParts(1)
End If
strCheckDate = arrDateParts(0) & "/" & arrDateParts(1) & "/" & arrDateParts(2)
If InStr(strDescription, strCheckDate) > 0 Then
boolDateFound = True
varYes = varYes + 1
Exit For
Else
varNo = varNo + 1
End If
Next
'End Nathan Rice Code
rsCheckYesNo.MoveNext
Loop
%>
<tbody>
<tr>
<td><%=strPersonName%></td>
<td><%=varYes%></td>
<td><%=varNo%></td>
<td><%=(varYes + varNo)%></td>
</tr>
</tbody>
<%
varYesTotal = varYesTotal + varYes
varNoTotal = varNoTotal + varNo
rsPerson.MoveNext
Loop
rsPerson.Close
%>
<tfoot>
<tr>
<td>Total</td>
<td><%=varYesTotal%></td>
<td><%=varNoTotal%></td>
<td><%=(varYesTotal+varNoTotal)%></td>
</tr>
</tfoot>
</table>
<%
End If
%>

Your plan should look like this:
PreP for whole task
Database
Date range
Total
Print header
Get persons
For all persons
PreP for person
Get name
Get descriptions
For all descriptions
Check and count
Next
PostP for person
Compute yes/no/all (one from two)
Print row
Update total
Next
PostP for whole task
Print total
Database
Looks like your code lacks the description loop.
Update:
In code:
Option Explicit
Dim greDate : Set greDate = New RegExp
greDate.Global = True
greDate.Pattern = "(\d{2})/(\d{2})/(\d{4})" ' dd/mm/yyyy
Dim aTotal : aTotal = Array(0,0,0)
Dim aTests : aTests = Array( _
Array( "peter" _
, "In 21/02/2014 something happened") _
, Array( "paul" _
, "pi 19/02/2014 pa 26/02/2014 po" _
, "In 21/02/2013 something happened") _
, Array( "mary" _
, "pi 19/02/2014 pu 20/02/2014 25/02/2014 26/02/2014 po" _
, "pi 19/02/2014 pu 20/02/2014 ") _
)
Dim aPers
Dim dtFrom : dtFrom = #2/20/2014#
Dim dtTo : dtTo = #2/25/2014#
For Each aPers In aTests
WScript.Echo "#####", aPers(0)
Dim aPSum : aPSum = Array(0, 0, 0)
Dim nDescr
For nDescr = 1 To UBound(aPers)
Dim sTest : sTest = aPers(nDescr)
WScript.Echo "-----", qq(sTest)
Dim aDates : aDates = getDatesFrom(sTest, dtFrom, dtTo)
If -1 = UBound(aDates) Then
WScript.Echo " no interesting dates found."
aPSum(1) = aPSum(1) + 1
Else
WScript.Echo " found (m/d/yyyy!)", Join(aDates, ", ")
aPSum(0) = aPSum(0) + 1
End If
Next
aPSum(2) = aPSum(0) + aPSum(1)
WScript.Echo "*****", Join(aPSum)
Dim i
For i = 0 To UBound(aTotal) : aTotal(i) = aTotal(i) + aPSum(i) : Next
Next
WScript.Echo "#####", Join(aTotal)
Function getDatesFrom(sText, dtFrom, dtTo)
ReDim aTmp(-1)
Dim oMTS : Set oMTS = greDate.Execute(sText)
Dim oMT, dtFound
For Each oMT In oMTS
' dd/mm/yyyy
dtFound = DateSerial(CInt(oMT.SubMatches(2)), cInt(oMT.SubMatches(1)), CInt(oMT.SubMatches(0)))
If dtFound >= dtFrom And dtFound <= dtTo Then
ReDim Preserve aTmp(Ubound(aTmp) + 1)
aTmp(Ubound(aTmp)) = dtFound
End If
Next
getDatesFrom = aTmp
End Function
Function qq(s) : qq = """" & s & """" : End Function
output:
cscript 21994835-2.vbs
##### peter
----- "In 21/02/2014 something happened"
found (m/d/yyyy!) 2/21/2014
***** 1 0 1
##### paul
----- "pi 19/02/2014 pa 26/02/2014 po"
no interesting dates found.
----- "In 21/02/2013 something happened"
no interesting dates found.
***** 0 2 2
##### mary
----- "pi 19/02/2014 pu 20/02/2014 25/02/2014 26/02/2014 po"
found (m/d/yyyy!) 2/20/2014, 2/25/2014
----- "pi 19/02/2014 pu 20/02/2014 "
found (m/d/yyyy!) 2/20/2014
***** 2 0 2
##### 3 2 5

Related

Optimizing Copy and Paste from one workbook to another in VBA

I have several .xlsm templates in a folder. I'm trying to read through all the excel files in that folder and based on the type of the file, it reads through all the sheets in each file and copy specific cells into another my active workbook (ThisWorkbook).
Following is my code and it is working correctly. However it is super slow. I'm looking for any solution that can speed up the code. I've already tried Application.ScreenUpdating = False but still it is very slow. It takes about 10 min for 20 files to be processed.
DO you guys have any suggestion on how to increase the speed.
Thanks Veru mich in Advance
...
Application.ScreenUpdating = False
FileType = "*.xls*"
OutputRow = 5
Range("$B$6:$M$300").ClearContents
filepath = Range("$B$3") & "\"
ThisWorkbook.ActiveSheet.Range("B" & OutputRow).Activate
OutputRow = OutputRow + 1
Curr_File = Dir(filepath & FileType)
Do Until Curr_File = ""
Set FldrWkbk = Workbooks.Open(filepath & Curr_File, False, True)
ThisWorkbook.ActiveSheet.Range("B" & OutputRow) = Curr_File
OutputRow = OutputRow
For Each sht In FldrWkbk.Sheets
ThisWorkbook.ActiveSheet.Range("C" & OutputRow) = sht.Name
If Workbooks(Curr_File).Worksheets(sht.Name).Range("B7") = "Project Number" Then
For i = 1 To 4
If IsEmpty(Workbooks(Curr_File).Worksheets(sht.Name).Cells(10, 5 + 2 * i)) = False Then
With Workbooks(Curr_File).Worksheets(sht.Name)
MyE = .Cells(10, 5 + 2 * i).Value
MyF = .Cells(11, 5 + 2 * i).Value
End With
With ThisWorkbook.ActiveSheet
.Range("D" & OutputRow).Value = "Unit Weight"
.Range("E" & OutputRow).Value = MyE
.Range("F" & OutputRow).Value = MyF
End With
OutputRow = OutputRow + 1
End If
Next
OutputRow = OutputRow - 1
ElseIf Workbooks(Curr_File).Worksheets(sht.Name).Range("C6") = "PROJECT NUMBER" Then
With Workbooks(Curr_File).Worksheets(sht.Name)
MyE = .Range("$H$9").Value
MyF = .Range("$B$9").Value
End With
With ThisWorkbook.ActiveSheet
.Range("D" & OutputRow).Value = "Specific Gravity"
.Range("E" & OutputRow).Value = MyE
.Range("F" & OutputRow).Value = MyF
End With
ElseIf Workbooks(Curr_File).Worksheets(sht.Name).Range("C6") = "Project Number" Then
With Workbooks(Curr_File).Worksheets(sht.Name)
MyE = .Range("$E$4").Value
MyF = .Range("$R$4").Value
MyG = .Range("$R$5").Value
End With
With ThisWorkbook.ActiveSheet
.Range("D" & OutputRow).Value = "Sieve & Hydrometer"
.Range("E" & OutputRow).Value = MyE
.Range("F" & OutputRow).Value = MyF
.Range("G" & OutputRow).Value = MyG
End With
ElseIf Workbooks(Curr_File).Worksheets(sht.Name).Range("A6") = "PROJECT NUMBER" Then
ThisWorkbook.ActiveSheet.Range("D" & OutputRow).Value = "Moisture Content"
Last = Workbooks(Curr_File).Worksheets(sht.Name).Cells(Rows.Count, "J").End(xlUp).Row
ThisWorkbook.ActiveSheet.Range("I" & OutputRow).Value =
Workbooks(Curr_File).Worksheets(sht.Name).Cells(Last, 10)
ElseIf Workbooks(Curr_File).Worksheets(sht.Name).Range("C5") = "Project Number" Then
With Workbooks(Curr_File).Worksheets(sht.Name)
MyE = .Range("$H$8").Value
MyF = .Range("$B$8").Value
MyG = .Range("$D$8").Value
End With
With ThisWorkbook.ActiveSheet
.Range("D" & OutputRow).Value = "Atterberg Limits"
.Range("E" & OutputRow).Value = MyE
.Range("F" & OutputRow).Value = MyF
.Range("G" & OutputRow).Value = MyG
End With
ElseIf Workbooks(Curr_File).Worksheets(sht.Name).Range("B5") = "Project Number" Then
With Workbooks(Curr_File).Worksheets(sht.Name)
MyE = .Range("$G$4").Value
MyF = .Range("$E$4").Value
MyG = .Range("$E$5").Value
End With
With ThisWorkbook.ActiveSheet
.Range("D" & OutputRow).Value = "Gradation Size"
.Range("E" & OutputRow).Value = MyE
.Range("F" & OutputRow).Value = MyF
.Range("G" & OutputRow).Value = MyG
End With
End If
OutputRow = OutputRow + 1
Next sht
FldrWkbk.Close SaveChanges:=False
Curr_File = Dir
Loop
Set FldrWkbk = Nothing
Application.ScreenUpdating = True
...
I Just realized that the slow performance is due to the formulations that are written in the excel but are linked to the ranges that are pasted from the Macro code. As it was addressed in the previous stack overflow solutions, I simply added "Application.Calculation = xlCalculationManual" in the beginning of the code and "Application.Calculation = xlCalculationAutomatic" at the end of the code and now it is much much faster.
I hope it is also useful to whom is reading this

How Export fpspread to Excel vb6?

I try to export to Excel with the fpsread plugin, but there really is no information on how, I have searched the manual but they only show me how to do it with .net
Will someone have an idea?
I managed to do it was very simple, but wanting to import the titles was the heaviest, but here I leave the code in case any work
Private Sub CmdImportar_Click()
Call Export_Excel(cdgExcel, sprFacturas)
Call HacerBusqueda
End Sub
Public Sub Export_Excel(cdgExcel As CommonDialog, Spread As fpSpread)
Dim Header() As String
Dim I As Integer
Dim j As Integer
Dim x As Integer
With cdgExcel
.CancelError = False
.InitDir = "C:/:"
.Filter = "Excel(*.xls)|*.xls"
.ShowSave
If .filename <> "" Then
Spread.Redraw = False
For I = 1 To Spread.ColHeaderRows
ReDim Header(Spread.MaxCols) As String
Spread.Row = SpreadHeader + (I - 1)
For j = 1 To Spread.MaxCols
Spread.Col = j
Header(j) = Spread.Text & ""
Next j
Spread.MaxRows = Spread.MaxRows + 1
Spread.Row = I
Spread.Action = ActionInsertRow
For j = 1 To Spread.MaxCols
Spread.Col = j
Spread.CellType = Spread.CellType
Spread.TypeHAlign = Spread.TypeHAlign
Spread.TypeVAlign = Spread.TypeVAlign
Spread.Text = Header(j) & ""
Next j
Next I
x = Spread.ExportToExcel(.filename, "Sheet1", "")
For I = 1 To Spread.ColHeaderRows
Spread.Row = 1
Spread.Action = ActionDeleteRow
Next I
If x = True Then
MsgBox .filename & vbNewLine & "Se ha Importado el archivo", vbInformation, "Resultado"
Else
MsgBox "No se ha podido exportar el archivo", vbCritical, "Error"
End If
End If
End With
End Sub

Import XML Data thru MSFlexigrid to SQL Table using vb6

My VB6 code reads XML file
loads into MSFLEXIGRID
loops through each record, if I see a break point,
does not add data in sql table except one record why it is happening does not know. does not throw any error.
I'm appending my code below:
Private Sub cmdPrint_Click()
Dim rsMtrData As New ADODB.Recordset
Dim irow As Integer
rsClose rsMtrData
rsMtrData.Open "select * from Master_Meter_Reading ", cn, adOpenKeyset, adLockPessimistic
With MSFlexGrid1
rsMtrData.AddNew
For irow = 0 To .Rows - 1
.Row = irow
.Col = 0
rsMtrData!Snapshot = .text & ""
.Col = 1
rsMtrData!LoadSurveyDTime = Format(.text, "dd-MM-yyyy hh:mm:SS")
.Col = 2
rsMtrData!LoadSurveyDateDay = g_ConvertNumber(.text)
.Col = 3
rsMtrData!LoadSurveyDate = Format(.text, g_DateFormat)
.Col = 4
rsMtrData!LoadSurveyDateParmVal = g_ConvertNumber(.text)
.Col = 5
rsMtrData!LoadSurveyType = .text & ""
.Col = 6
rsMtrData!LoadSurveyUnit = g_ConvertNumber(.text)
.Col = 7
rsMtrData!LoadSurveySlipValParmVal = .text & ""
.Col = 8
rsMtrData!LoadSurveySlipValParmValTime = g_ConvertNumber(.text)
rsMtrData.Update
Next irow
End With
MsgBox "Data Successfully Saved", vbInformation
End Sub
You are only adding one record then updating it. At the moment the AddNew is on the outside of the loop. If you change the code and move the AddNew inside the For..Next loop it should add more rows.
Your code would look something like this:
Private Sub cmdPrint_Click()
Dim rsMtrData As New ADODB.Recordset
Dim irow As Integer
rsClose rsMtrData
rsMtrData.Open "select * from Master_Meter_Reading ", cn, adOpenKeyset, adLockPessimistic
With MSFlexGrid1
For irow = 0 To .Rows - 1
rsMtrData.AddNew 'This is the line that has moved from outside to inside the loop.
.Row = irow
.Col = 0
rsMtrData!Snapshot = .text & ""
.Col = 1
rsMtrData!LoadSurveyDTime = Format(.text, "dd-MM-yyyy hh:mm:SS")
.Col = 2
rsMtrData!LoadSurveyDateDay = g_ConvertNumber(.text)
.Col = 3
rsMtrData!LoadSurveyDate = Format(.text, g_DateFormat)
.Col = 4
rsMtrData!LoadSurveyDateParmVal = g_ConvertNumber(.text)
.Col = 5
rsMtrData!LoadSurveyType = .text & ""
.Col = 6
rsMtrData!LoadSurveyUnit = g_ConvertNumber(.text)
.Col = 7
rsMtrData!LoadSurveySlipValParmVal = .text & ""
.Col = 8
rsMtrData!LoadSurveySlipValParmValTime = g_ConvertNumber(.text)
rsMtrData.Update
Next irow
End With
MsgBox "Data Successfully Saved", vbInformation
End Sub

Microsoft Acess VBA Debug Object Variable With Block Not Set

I have the below procedure and I am getting a Object Variable With Block Net Set Debug. I have reviewed it and just can find how to solve it. Any suggestions?
It debugs a little over half way down where I put the comment 'The Code Debugs at Do Until rstMaster.EOF.
Your help is much appreciated.
Sub AllocateImmediately()
Dim x As Long
Dim y As Long
Dim z As Long
Dim sMonths(1 To 12) As String
Dim lAllocation As Long
Dim iMonth As Integer
Dim iCurrentMonth As Integer
Dim sCurrentDLRNumber As String
Dim iAlreadyAllocated As Integer
Dim j As Integer
Dim sDealerID As String
Dim iPriorProduction As Integer
Dim iAllocation As Integer
'Assign Month names to be used when writing to the master table
sMonths(1) = "January"
sMonths(2) = "February"
sMonths(3) = "March"
sMonths(4) = "April"
sMonths(5) = "May"
sMonths(6) = "June"
sMonths(7) = "July"
sMonths(8) = "August"
sMonths(9) = "September"
sMonths(10) = "October"
sMonths(11) = "November"
sMonths(12) = "December"
Dim iTotalProduction As Long
Dim iLastMonth As Integer
'Dim iCurrentMonth As Integer
'Dim iLastMonth As Integer
Dim iStartingMonth As Integer
Dim rstAllocations As Recordset
Dim rstMaster As Recordset
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim Fld As DAO.Field
Dim strField As String
Dim iProduction As Integer
Dim k As Integer
Dim o As Integer
Dim i As Integer
'Dim iAllocation As Integer
Dim sCurrentModel As String
Dim sSpec As String
Dim sFilter As String
Dim sPreviousModel As String
Dim sPreviousSpec As String
Dim iMonthTry As Integer
If Not IsNull(cboStartingProductionMonth.Value) Then 'check to see starting month was selected.
iStartingMonth = cboStartingProductionMonth.Value
Else
MsgBox "Please use the drop down box and select the starting month.", vbCritical
End
End If
Set rstAllocations = CurrentDb.OpenRecordset("select * from Allocations order by [Model Name],[Spec]") 'Loop through allocations table for each model
Do Until rstAllocations.EOF
sCurrentModel = rstAllocations("Model Name")
sSpec = IIf(IsNull(rstAllocations("Spec")) Or rstAllocations("Spec") = "", "", rstAllocations("Spec"))
sFilter = ""
'At the last record
rstAllocations.MoveNext
If rstAllocations.EOF = True Then
rstAllocations.MovePrevious
Else
rstAllocations.MovePrevious
End If
If Not (rstAllocations.EOF) Then
rstAllocations.MoveNext
If rstAllocations.EOF Then
rstAllocations.MovePrevious
'at the last record it is either "CA" or "All" due to sort order.
If sPreviousModel = sCurrentModel And sSpec = "CA" Then sFilter = "CA"
If sFilter <> "" Then GoTo sSQLStatements
GoTo NextTry:
End If
If sCurrentModel = rstAllocations("Model Name") Then sFilter = "AllButCA" 'Going to be a CA model next round
rstAllocations.MovePrevious
If sFilter <> "" Then GoTo sSQLStatements
End If
NextTry:
If Not (rstAllocations.EOF) Then
rstAllocations.MoveNext
If rstAllocations.EOF Then
rstAllocations.MovePrevious
If sPreviousModel <> sCurrentModel And sSpec = "CA" Then sFilter = "CA"
If sFilter <> "" Then GoTo sSQLStatements
GoTo NextTry2:
End If
If sCurrentModel <> rstAllocations("Model Name") And sSpec = "CA" Then sFilter = "CA" 'only a CA model needs to be filtered
rstAllocations.MovePrevious
If sFilter <> "" Then GoTo sSQLStatements
End If
NextTry2:
If Not (rstAllocations.EOF) Then
rstAllocations.MoveNext
If rstAllocations.EOF Then
rstAllocations.MovePrevious
If sPreviousModel <> sCurrentModel And sSpec = "" Then sFilter = "ALL"
If sFilter <> "" Then GoTo sSQLStatements
End If
If sCurrentModel <> rstAllocations("Model Name") And (IsNull(sSpec) Or sSpec = "") Then sFilter = "ALL" 'only a CA model needs to be filtered
rstAllocations.MovePrevious
If sFilter <> "" Then GoTo sSQLStatements
End If
sSQLStatements:
sDealerID = "" 'Reset Dealer
iProduction = 0 'Reset Production
iTotalProduction = 0
k = 0
iMonth = 0
sPreviousModel = sCurrentModel
sPreviousSpec = sSpec
'create recordset based on if the recordset should filter on CA, All states, or All But CA depending on Specs for a particular model.
Select Case UCase(sFilter)
Case "ALL"
Set rstMaster = CurrentDb.OpenRecordset("Select * from tblMaster where [New Model] = " & "'" & rstAllocations("Model Name") & "'" & " AND [Alloc Calculation]>0 order by [Alloc Calculation] desc, [Months Supply Model] ASC")
Case "CA"
Set rstMaster = CurrentDb.OpenRecordset("Select * from tblMaster where [New Model] = " & "'" & rstAllocations("Model Name") & "'" & " AND [Alloc Calculation]>0 and [STATE_NAME] ='CA' order by [Alloc Calculation] desc, [Months Supply Model] ASC")
Case "ALLBUTCA"
Set rstMaster = CurrentDb.OpenRecordset("Select * from tblMaster where [New Model] = " & "'" & rstAllocations("Model Name") & "'" & " AND [Alloc Calculation]>0 and [STATE_NAME] <>'CA' order by [Alloc Calculation] desc, [Months Supply Model] ASC")
End Select
iCurrentMonth = iStartingMonth - 1
'calculate total production in the allocations table for a model for all months.
For o = 1 To 12
iTotalProduction = IIf(IsNull(rstAllocations(sMonths(o))), 0, rstAllocations(sMonths(o))) + iTotalProduction
''debug.print iTotalProduction, sMonths(o), rstMaster("New Model")
Next o
GetAnotherMonth:
iMonthTry = iMonthTry + 1
'---Handle Months---------------Loops through months
iMonth = iMonth + 1
If iMonth = 13 And rstAllocations.EOF Then
Exit Do
ElseIf iMonth = 13 Then
GoTo kIsOver12:
End If
iCurrentMonth = iCurrentMonth + 1
If iCurrentMonth = 13 Then iCurrentMonth = 1 'Month can be greater than
'---Handle Months---------------
k = iCurrentMonth
'If k > 12 Then GoTo kIsOver12:
iProduction = IIf(IsNull(rstAllocations(sMonths(k))), 0, rstAllocations(sMonths(k))) + iProduction 'add production that can be allocated.
If sDealerID <> "" Then 'move to the previous dealership that recived an allocation and move to the next dealer in line.
rstMaster.MoveFirst
rstMaster.FindFirst "[DLR_NO]= " & "'" & sDealerID & "'"
rstMaster.MoveNext
If rstMaster.EOF Then
rstMaster.MoveFirst
' Else
' rstMaster.MoveNext
End If
End If
'If iProduction = 0 Then GoTo GetAnotherMonth
'The Code Debugs Here
Do Until rstMaster.EOF
TryToAllocateAgain:
If iProduction = 0 Then 'production for that month has ran out.
GoTo GetAnotherMonth:
End If
'--Does Dealer already have his allocated amount?--
iAlreadyAllocated = 0
For j = 1 To 12
iAlreadyAllocated = rstMaster(sMonths(j) & " Allocation") + iAlreadyAllocated
Next j
If iAlreadyAllocated + iNumberPerOrder(i) > rstMaster("Alloc Calculation") Then
''debug.print iAlreadyAllocated, rstMaster("Alloc Calculation")
GoTo NextRecord 'Only assign upto their alloc calc, don't assign another
End If
'--Does Dealer already have his allocated amount?--
With rstMaster
sDealerID = rstMaster("DLR_No")
For i = 0 To iTotalNumberofModels - 1 'Match Model being assigned with the number per order
If rstMaster("New Model") = sBaseModel(i) Or rstMaster("New Model") = sLimitedEdition(i) Then
iAllocation = iNumberPerOrder(i):: Exit For
End If
Next i
'remove one from both iProduction and iTotalProduction
iProduction = iProduction - iNumberPerOrder(i)
iTotalProduction = iTotalProduction - iNumberPerOrder(i)
If iProduction < 0 Then 'if that month's production is out, add back to the itotalproduction
iTotalProduction = iTotalProduction + iNumberPerOrder(i) 'since inumberperorder(i) was subtracted above.
GoTo GetAnotherMonth
End If
.Edit
rstMaster(sMonths(iCurrentMonth) & " Allocation") = rstMaster(sMonths(iCurrentMonth) & " Allocation") + iNumberPerOrder(i)
.Update
' If iMonthTry <= 12 And iTotalProduction > 0 Then GoTo GetAnotherMonth 'added to loop through to make sure all months have been allocated
' If iMonthTry >= 12 Then iMonthTry = 0
'.MoveNext
End With
NextRecord:
rstMaster.MoveNext
If iTotalProduction > 0 And rstMaster.EOF And iMonthTry < 12 Then
sDealerID = ""
rstMaster.MoveFirst
GoTo GetAnotherMonth
End If
Loop
'If there are left over models during a month, attempt to allocate them again until the iProduction is equal to production
'meaning no more could be allocated.
If iProduction > 0 And rstMaster.EOF And iPriorProduction <> iProduction Then
iPriorProduction = iProduction
rstMaster.MoveFirst
GoTo TryToAllocateAgain
End If
kIsOver12:
''debug.print rstAllocations("Model Name") & " " & Trim(Str(iTotalProduction)), iPriorProduction
iPriorProduction = 0
iMonthTry = 0
rstAllocations.MoveNext
Loop
End Sub
that's a strange error, even if you speak english. maybe this will help:
"Object variable or With block variable not set"
i think that's right. it means a with-block (a block that starts with 'with') is needed. hopefully that will help a bit. possibly With rstMaster...End With
error (msdn)
with...end statement (msdn)
The error is very likely being causes by your goto statements. eg
This line
GoTo TryToAllocateAgain
causes the next executable statement to be one inside a loop. This is not allowed
Similarly
GoTo TryToAllocateAgain
jumps out of a loop.
You need to rethinkt he structure of your code. Try and create a mani procedure that calls other functions as required (with all data required by the function being passed to it as parameters)
Also note you can assign Month names in one line like this
sMonths = Split("Jan,Feb,Mar,etc", ",")
Also consider the block. The "nesting" of if statements could be very much simplified.
If rstAllocations.EOF = True Then ''' MovePrevious always done!
rstAllocations.MovePrevious
Else
rstAllocations.MovePrevious
End If
If Not (rstAllocations.EOF) Then '''OPPOSITE - use else!
rstAllocations.MoveNext
If rstAllocations.EOF Then
rstAllocations.MovePrevious
'at the last record it is either "CA" or "All" due to sort order.
If sPreviousModel = sCurrentModel And sSpec = "CA" Then sFilter = "CA"
If sFilter <> "" Then GoTo sSQLStatements
GoTo NextTry:
End If
If sCurrentModel = rstAllocations("Model Name") Then sFilter = "AllButCA" 'Going to be a CA model next round
rstAllocations.MovePrevious
If sFilter <> "" Then GoTo sSQLStatements
End If

Convert Seconds to Weeks, Days, Hours, Minutes, Seconds in VBScript

Is there a function to convert a specified number of seconds into a week/day/hour/minute/second time format in vbscript?
eg: 969234 seconds = 1wk 4days 5hrs 13mins 54secs
Dim myDate
dim noWeeks
dim noDays
dim tempWeeks
dim pos
myDate = DateAdd("s",969234,CDate(0))
tempWeeks = FormatNumber(myDate / 7,10)
pos = instr(tempWeeks, ".")
if pos > 1 then
tempWeeks = left(myDate, pos -1)
end if
noWeeks = Cint(tempWeeks)
noDays = Cint(((myDate / 7) - noWeeks) * 7)
wscript.echo noWeeks & "wk " & noDays & "days " & datepart("h", myDate) & "hrs " & datepart("n", myDate) & "mins " & datepart("s", myDate) & "secs"
No built in function to do that.
Here is a quick and dirty one:-
Function SecondsToString(totalSeconds)
Dim work : work = totalSeconds
Dim seconds
Dim minutes
Dim hours
Dim days
Dim weeks
seconds = work Mod 60
work = work \ 60
minutes = work Mod 60
work = work \ 60
hours = work Mod 24
work = work \ 24
days = work Mod 7
work = work \ 7
weeks = work
Dim s: s = ""
Dim renderStarted: renderStarted = False
If (weeks <> 0) Then
renderStarted = True
s = s & CStr(weeks)
If (weeks = 1) Then
s = s & "wk "
Else
s = s & "wks "
End If
End If
If (days <> 0 OR renderStarted) Then
renderStarted = True
s = s & CStr(days)
If (days = 1) Then
s = s & "day "
Else
s = s & "days "
End If
End If
If (hours <> 0 OR renderStarted) Then
renderStarted = True
s = s & CStr(hours)
If (hours = 1) Then
s = s & "hr "
Else
s = s & "hrs "
End If
End If
If (minutes <> 0 OR renderStarted) Then
renderStarted = True
s = s & CStr(minutes)
If (minutes = 1) Then
s = s & "min "
Else
s = s & "mins "
End If
End If
s = s & CStr(seconds)
If (seconds = 1) Then
s = s & "sec "
Else
s = s & "secs "
End If
SecondsToString = s
End Function
You wantto use timer pseudo-variable :
start = timer
Rem do something long
duration_in_seconds = timer - start
wscript.echo "Duration " & duration_in_seconds & " seconds."

Resources