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
Related
Private Sub AddToOutline(ol As Object, psModel As String, pnKeyOfNode As Long, pnStmtRef As Long, pnLabCount, psFT As Variant, pnFV As Variant, psFV As Variant, pvStatus As Variant, pbExpand As Boolean)
Dim sStmt As String 'Stores the VCA Statement node for adding to the outline
Dim sLabel As String 'Store the VCA Label node for adding to the outline
Dim outidxS As Integer 'outline pointer for the statement
Dim outidxL As Integer 'outline pointer for the label
Dim i As Integer
Dim nPos As Integer
'psModel is optional
If psModel <> "" Then
LocateModel ol, psModel
End If
'First array element should be a MARQUE label
If psFT(0) <> FT_MARQUE Then
MsgBox "WARNING: VCA Statement " & pnStmtRef & " is Missing its Marque VCA Label"
Exit Sub
End If
'Second Array element must be the MODEL RANGE Label
If psFT(1) <> FT_MODEL_RANGE Then
MsgBox "WARNING: VCA Statement " & pnStmtRef & " is Missing its Model Range VCA Label"
Exit Sub
End If
'----------------------------------------------------------
' FIRST: Add the VCA Statement Node to the Outline
'----------------------------------------------------------
'Add the VCA Statement Status if provided
If Not IsNull(pvStatus) Then
If pvStatus <> "A" Then
sStmt = sStmt & OL_STMT_UNAVAILABLE & " "
End If
End If
'Set the Statement Number
sStmt = sStmt & pnStmtRef
If pnLabCount = 2 Then
sStmt = sStmt & " (Whole Model)"
Else
'Build up Statement string (e.g. "10001 -> T Series + Turbo Charger Fitted")
sStmt = sStmt & " -> "
For i = 2 To pnLabCount - 1
If i > 2 Then sStmt = sStmt & " + "
sStmt = sStmt & psFV(i)
Next i
End If
'Add The VCA Statement Node to the Outline
ol.AddItem sStmt
ol.Expand(ol.ListIndex) = pbExpand 'Optionally expand the VCA Statement node
'Re-position to newly added item
'The picturetype is include in the condition on the loop
'to cater for the fact that sStmt may not be unique on its own
outidxS = ol.ListIndex
Do
outidxS = outidxS + 1
Loop Until ol.List(outidxS) = sStmt And ol.PictureType(outidxS) <> 1
ol.ListIndex = outidxS
'9/10/97 ol.ItemData(outidxS) = pnStmtRef 'Store Statement ref as the key
ol.ItemData(outidxS) = pnKeyOfNode 'Store Statement ref as the key
ol.indent(outidxS) = 2
ol.PictureType(outidxS) = 1
'----------------------------------------------------------
' SECOND: Add each of the VCA Label Nodes to the Outline
'----------------------------------------------------------
'Only needed if more than 2 labels, i.e more than just Marque and Model Range labels
If pnLabCount > 2 Then
For i = 2 To pnLabCount - 1
'Add the VCA Label to the Outline
sLabel = psFT(i) & " = " & psFV(i)
ol.AddItem sLabel, ol.ListIndex + 1
outidxL = ol.ListIndex + 1
ol.ItemData(outidxL) = pnFV(i) 'Store the VCA_LAB_REF as the key
ol.indent(outidxL) = 3
ol.PictureType(outidxL) = 2
ol.ListIndex = outidxL
Next i
End If 'pnLabCount
'Reset Position in tree
ol.ListIndex = outidxS
End Sub
'Re-position an Outline Control to the supplied Model
'If not found then the Model will be added to the Outline
Public Sub LocateModel(ol As Object, psModel As String)
Dim i As Integer
'Try and find the same Model in the Outline
**ol.ListIndex = -1**
For i = 0 To ol.ListCount - 1
If ol.indent(i) = 1 Then
If ol.List(i) = psModel Then
ol.ListIndex = i
Exit For
End If
End If '.indent
Next i
'If Model Not found ...
If ol.ListIndex = -1 Then
ol.AddItem psModel
ol.ListIndex = ol.ListCount - 1
I'm trying to get the date from an attribute called 'accountExpires' of a computer object in Active Directory. If the object haven't been set it just says 'never' and if you look it just have a many numbers. I made this and it working for the attribute 'lastlogon', but not for 'accountExpires'. Maybe someone can help me out.
I'm using VBscript because our company is using this in our loginscript.
On Error Resume Next
Dim ADSysInfo, objComputer, lobjDate, laccountExpiresDate, WSHShell
Set WSHShell = CreateObject("WScript.Shell")
Set ADSysInfo = CreateObject("ADSystemInfo")
Set objComputer = GetObject("LDAP://" & ADSysInfo.ComputerName)
msgbox objComputer
Set lobjDate = objComputer.get("lastLogon") ' <----- Working ----->
' Set lobjDate = objComputer.get("accountExpires") ' <----- Not Working ----->
msgbox err.number
if IsNull(lobjDate) then
msgbox "No Date"
else
laccountExpiresDate = Integer8Date(lobjDate, getLocaltimeZoneBias)
msgbox laccountExpiresDate
end if
Function Integer8Date(objDate, lngBias)
' Function to convert Integer8 (64-bit) value to a date, adjusted for
' local time zone bias.
Dim lngAdjust, lngDate, lngHigh, lngLow
lngAdjust = lngBias
lngHigh = objDate.HighPart
lngLow = objdate.LowPart
' Account for bug in IADslargeInteger property methods.
If lngLow < 0 Then
lngHigh = lngHigh + 1
End If
If (lngHigh = 0) And (lngLow = 0) Then
lngAdjust = 0
End If
lngDate = #1/1/1601# + (((lngHigh * (2 ^ 32)) + lngLow) / 600000000 - lngAdjust) / 1440
Integer8Date = CDate(lngDate)
End Function
' Obtain local time zone bias from machine registry.
Function getLocaltimeZoneBias
Dim lngBiasKey, lngBias
lngBiasKey = WSHShell.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
If UCase(TypeName(lngBiasKey)) = "LONG" Then
lngBias = lngBiasKey
ElseIf UCase(TypeName(lngBiasKey)) = "VARIANT()" Then
lngBias = 0
For k = 0 To UBound(lngBiasKey)
lngBias = lngBias + (lngBiasKey(k) * 256^k)
Next
End If
getLocaltimeZoneBias = lngBias
End Function 'getLocaltimeZoneBias
There's a few posts on this, but none seem to provide a whole code solution, so I'm posting this up, which is culled (and credited where appropriate) from various bits and pieces of ideas on the Internet. VB6 doesn't have any function to convert from a fraction to a decimal number, which I needed for a project that I was working on which was concerned with meal recipes. I considered writing a DLL in .NET and plugging it into my application, but decided on this approach in the end. I hope this is useful for others. The solution below will do the following:
You supply a decimal number and you will be returned the fraction as a string.
You supply a fraction as a string and you will be returned with the decimal number.
In both cases, whole numbers are accounted for eg. "2 3/4" (two and three quarters) or "2.75".
I'm sure the code is not efficient, so any improvements are welcome.
Copy/Paste this as a new Class module:
Option Explicit
Private ErrorNote As String
'Properties
Public Property Get GetAsFraction(numToConvert As Double) As String
On Error GoTo GetAsFraction_Error
GetAsFraction = FncGetAsFraction(numToConvert)
On Error GoTo 0
Exit Property
GetAsFraction_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'GetAsFraction' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Property
Public Property Get GetAsDecimal(fractionString As String) As Double
On Error GoTo GetAsDecimal_Error
GetAsDecimal = FncGetAsDecimal(fractionString)
On Error GoTo 0
Exit Property
GetAsDecimal_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'GetAsDecimal' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Property
'Functions - private
Private Function FncGetAsDecimal(fractionToConvert As String) As Double
Dim result As Double
Dim wholeNumber As Integer
Dim splitStr As Variant
Dim numerator As Integer
Dim denominator As Integer
Dim fractionString As String
Dim dividedByPos As Integer
On Error GoTo FncGetAsDecimal_Error
splitStr = Split(fractionToConvert, " ")
If UBound(splitStr) = 1 Then
wholeNumber = splitStr(0)
fractionString = splitStr(1)
Else
fractionString = splitStr(0)
End If
dividedByPos = InStr(1, fractionString, "/")
numerator = Left(fractionString, dividedByPos - 1)
denominator = Mid(fractionString, dividedByPos + 1)
result = Val(numerator) / Val(denominator) + wholeNumber
FncGetAsDecimal = result
On Error GoTo 0
Exit Function
FncGetAsDecimal_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncGetAsDecimal' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
Private Function FncGetAsFraction(numToConvert As Double) As String
Dim result As String
Dim numeratorCount As Integer
Dim denominator As Single
Dim multiplierStr As String
Dim i As Integer
Dim fractionNum As Single
Dim lowestCommonDenominator As Long
Dim wholeNumber As Integer
Dim decimalPos As Integer
On Error GoTo FncGetAsFraction_Error
If numToConvert > 0 Then
decimalPos = InStr(1, CStr(numToConvert), ".")
If decimalPos > 1 Then
wholeNumber = CStr(Mid(numToConvert, 1, decimalPos - 1))
numToConvert = CStr(Mid(numToConvert, decimalPos))
End If
numeratorCount = FncCountDecimalPlaces(numToConvert)
multiplierStr = "1"
For i = 1 To numeratorCount
multiplierStr = multiplierStr & "0"
Next i
fractionNum = numToConvert * Val(multiplierStr)
denominator = 1 * Val(multiplierStr)
result = FncCrunchFraction(fractionNum, denominator)
If result = "" Then result = fractionNum & "/" & denominator
If wholeNumber <> 0 Then result = wholeNumber & " " & result
Else
result = "ERROR"
End If
FncGetAsFraction = result
On Error GoTo 0
Exit Function
FncGetAsFraction_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncGetAsFraction' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
Private Function FncCountDecimalPlaces(num As Double) As Integer
Dim result As Integer
Dim numberStr As String
Dim i As Integer
Dim decimalPointPos As Integer
On Error GoTo FncCountDecimalPlaces_Error
numberStr = CStr(num)
If Len(numberStr) > 0 Then
i = 1
Do While i <= Len(numberStr) And decimalPointPos = 0
If Mid(numberStr, i, 1) = "." Then decimalPointPos = i
i = i + 1
Loop
End If
If i > 1 Then
result = (Len(numberStr) - i + 1)
End If
FncCountDecimalPlaces = result
On Error GoTo 0
Exit Function
FncCountDecimalPlaces_Error:
ErrorNote = "Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncCountDecimalPlaces' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
'Credit to:
'http://www.tek-tips.com/viewthread.cfm?qid=206890
'dsi (Programmer) - 7 Feb 02 10:38
Private Function FncCrunchFraction(num1 As Single, num2 As Single) As String
Dim num As Single
Dim dem As Single
Dim cnt1 As Integer
Dim cnt2 As Integer
Dim numFactors() As Single
Dim demFactors() As Single
Dim common As Single
Dim i As Integer
Dim j As Integer
On Error GoTo FncCrunchFraction_Error
num = num1
dem = num2
For i = 2 To Int(num / 2) Step 1
If (num Mod i = 0) Then
cnt1 = cnt1 + 1
ReDim Preserve numFactors(1 To cnt1)
numFactors(cnt1) = i
End If
Next i
cnt1 = cnt1 + 1
ReDim Preserve numFactors(1 To cnt1)
numFactors(cnt1) = num
For i = 2 To Int(dem / 2) Step 1
If (dem Mod i = 0) Then
cnt2 = cnt2 + 1
ReDim Preserve demFactors(1 To cnt2)
demFactors(cnt2) = i
End If
Next i
cnt2 = cnt2 + 1
ReDim Preserve demFactors(1 To cnt2)
demFactors(cnt2) = dem
For i = cnt1 To 1 Step -1
For j = cnt2 To 1 Step -1
If (numFactors(i) = demFactors(j)) Then
common = numFactors(i)
FncCrunchFraction = num / common & "/" & dem / common
Exit Function
End If
Next j
Next i
FncCrunchFraction = ""
On Error GoTo 0
Exit Function
FncCrunchFraction_Error:
ErrorNote = "Line:" & Erl & " Number:" & Err.number & " (" & Err.Description & ") in procedure 'FncCrunchFraction' in 'ClsFractionDecimal'"
MsgBox (ErrorNote)
End Function
Then call it with these code examples:
Public Function DecimalToFraction(number As Double) As String
Dim myFractionDecimal As New ClsFractionDecimal
DecimalToFraction = myFractionDecimal.GetAsFraction(number)
Set myFractionDecimal = Nothing
End Function
Public Function FractionToDecimal(fractionString As String) As Double
Dim myFractionDecimal As New ClsFractionDecimal
FractionToDecimal = myFractionDecimal.GetAsDecimal(fractionString)
Set myFractionDecimal = Nothing
End Function
how can I write UTF-8 encoded strings to a textfile from VBScript? I have tried some variations but no success. So I need the text file saved in UTF-8 format. thanks in advance for your all help.
Output :
CN=™ser1 D˜,OU=TEST,OU=TEST,OU=Users,OU=contoso,DC=contoso,DC=local;10.01.2012 01:00:00
CN=Gšbson ¦LU,OU=TEST,OU=TEST,OU=Users,OU=contoso,DC=contoso,DC=local;20.12.2016 18:55:51
CN=™ZL €ET˜,OU=TEST,OU=TEST,OU=Users,OU=contoso,DC=contoso,DC=local;27.08.2013
type ExpReport.txt (as you can see no special characters)
CN=ser1 D,OU=TEST,OU=TEST,OU=Users,OU=contoso,DC=contoso,DC=local;10.01.2012 01:00:00
CN=Gbson LU,OU=TEST,OU=TEST,OU=Users,OU=contoso,DC=contoso,DC=local;20.12.2016 18:55:51
CN=ZL ET,OU=TEST,OU=TEST,OU=Users,OU=contoso,DC=contoso,DC=local;27.08.2013
cscript //nologo AcctsExpire.vbs > ExpReport.txt
Here is my code :
Option Explicit
Dim adoConnection, adoCommand
Dim objRootDSE, strDNSDomain, strFilter, strQuery, adoRecordset
Dim strDN, objShell, lngBiasKey, lngBias
Dim lngDate, objDate, dtmAcctExp, k
' Obtain local time zone bias from machine registry.
Set objShell = CreateObject("Wscript.Shell")
lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" _
& "TimeZoneInformation\ActiveTimeBias")
If (UCase(TypeName(lngBiasKey)) = "LONG") Then
lngBias = lngBiasKey
ElseIf (UCase(TypeName(lngBiasKey)) = "VARIANT()") Then
lngBias = 0
For k = 0 To UBound(lngBiasKey)
lngBias = lngBias + (lngBiasKey(k) * 256^k)
Next
End If
' Use ADO to search the domain for all users.
Set adoConnection = CreateObject("ADODB.Connection")
Set adoCommand = CreateObject("ADODB.Command")
adoConnection.Provider = "ADsDSOOBject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
' Determine the DNS domain from the RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
' Filter to retrieve all user objects with accounts
' that expire.
strFilter = "(&(objectCategory=person)(objectClass=user)" _
& "(!accountExpires=0)(!accountExpires=9223372036854775807))"
strQuery = "<LDAP://" & strDNSDomain & ">;" & strFilter _
& ";distinguishedName,accountExpires;subtree"
' Run the query.
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
Set adoRecordset = adoCommand.Execute
' Enumerate the recordset.
Do Until adoRecordset.EOF
strDN = adoRecordset.Fields("distinguishedName").Value
lngDate = adoRecordset.Fields("accountExpires")
Set objDate = lngDate
dtmAcctExp = Integer8Date(objDate, lngBias)
Wscript.Echo strDN & ";" & dtmAcctExp
adoRecordset.MoveNext
Loop
adoRecordset.Close
' Clean up.
adoConnection.Close
Function Integer8Date(ByVal objDate, ByVal lngBias)
' Function to convert Integer8 (64-bit) value to a date, adjusted for
' local time zone bias.
Dim lngAdjust, lngDate, lngHigh, lngLow
lngAdjust = lngBias
lngHigh = objDate.HighPart
lngLow = objdate.LowPart
' Account for bug in IADslargeInteger property methods.
If (lngLow < 0) Then
lngHigh = lngHigh + 1
End If
If (lngHigh = 0) And (lngLow = 0) Then
lngAdjust = 0
End If
lngDate = #1/1/1601# + (((lngHigh * (2 ^ 32)) _
+ lngLow) / 600000000 - lngAdjust) / 1440
Integer8Date = CDate(lngDate)
End Function
Last Update :
Issue is resolved.
cscript //nologo AcctsExpire.vbs //U > ExpReport.txt
Also WSCRIPT AcctsExpire.vbs displays correct output.
I want to make a program that gets user input and saves it in a text document, every time it saves a new document I want the file name to change
Here is what I have:
Option Explicit
Dim fso
Dim firstNameInput
Dim lastNameInput
Dim count
Dim testPath
Dim exists
Dim fileName
Dim fileStream
Dim filePath
Set fso = CreateObject("Scripting.FileSystemObject")
firstNameInput = inputbox("Please enter your name")
lastNameInput = inputbox("Enter your last name")
count = 1
do
testPath = "C:\Users\Me\Desktop\Info\peopleInfo" & count & ".txt"
exists = fso.FolderExists(testPath)
if(exists) then
count + 1
else
exit do
end if
loop
fileName = "peopleInfo" & count & ".txt"
filePath = "C:\Users\Me\Desktop\Info\"
Set fileStream = fso.CreateTextFile(filePath & fileName)
fileStream.WriteLine firstNameInput
fileStream.WriteLine lastNameInput
fileStream.Close
What I have doesn't seem to be working...
So every time I open this program, I want it to save the file as peopleInfo1 then peopleInfo2 then peopleInfo3 , etc.
Try something like that :
Option Explicit
Const RootFolder = "C:\Users\Me\Desktop\Info"
Dim fso,Folder,FirstFile,sFile,sFileNewName,firstNameInput,lastNameInput
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(RootFolder) Then
fso.CreateFolder(RootFolder)
End If
Set Folder = fso.GetFolder(RootFolder)
Do
firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""
Do
lastNameInput = inputbox("Enter your last name")
Loop Until lastNameInput <> ""
FirstFile = RootFolder &"\peopleInfo.txt"
If Not fso.FileExists(FirstFile) Then
Call Write2File(RootFolder & "\peopleInfo.txt")
Else
sFileNewName = GetNewName(FirstFile)
Call Write2File(sFileNewName)
End If
'************************************************************************************************************
Function GetNewName(sFile)
Dim snamebase,sname,Count,sTarget,MaxIncrementation
MaxIncrementation = 1000
snamebase = Split(Right(sFile, Len(sFile) - InStrRev(sFile,"\")),".")(0)
sname = snamebase
Count = 0
While Count < MaxIncrementation
sTarget = Folder & "\" & sname & ".txt"
If fso.FileExists(sTarget) Then
Count = Count + 1
sName = snamebase & "(" & Count & ")"
Else
GetNewName = sTarget
Exit Function
End If
Wend
End Function
'************************************************************************************************************
Sub Write2File(File)
Dim fileStream
Set fileStream = fso.CreateTextFile(File)
fileStream.WriteLine firstNameInput
fileStream.WriteLine lastNameInput
fileStream.Close
End Sub
'************************************************************************************************************
Or Something like that :
Option Explicit
Dim Ws,fso,RootFolder,Folder,FirstFile,sFile,sFileNewName,firstNameInput,lastNameInput,Desktop
Set Ws = CreateObject("Wscript.Shell")
RootFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%\Desktop\Info")
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(RootFolder) Then
fso.CreateFolder(RootFolder)
End If
Set Folder = fso.GetFolder(RootFolder)
Do
firstNameInput = inputbox("Please enter your name")
Loop Until firstNameInput <> ""
Do
lastNameInput = inputbox("Enter your last name")
Loop Until lastNameInput <> ""
FirstFile = RootFolder &"\peopleInfo.txt"
If Not fso.FileExists(FirstFile) Then
Call Write2File(RootFolder & "\peopleInfo.txt")
Else
sFileNewName = GetNewName(FirstFile)
Call Write2File(sFileNewName)
End If
'************************************************************************************************************
Function GetNewName(sFile)
Dim snamebase,sname,Count,sTarget,MaxIncrementation
MaxIncrementation = 1000
snamebase = Split(Right(sFile, Len(sFile) - InStrRev(sFile,"\")),".")(0)
sname = snamebase
Count = 0
While Count < MaxIncrementation
sTarget = Folder & "\" & sname & ".txt"
If fso.FileExists(sTarget) Then
Count = Count + 1
sName = snamebase & "(" & Count & ")"
Else
GetNewName = sTarget
Exit Function
End If
Wend
End Function
'************************************************************************************************************
Sub Write2File(File)
Dim fileStream
Set fileStream = fso.CreateTextFile(File)
fileStream.WriteLine firstNameInput
fileStream.WriteLine lastNameInput
fileStream.Close
End Sub
'************************************************************************************************************
The first problem is caused by your line:
exists = fso.FolderExists(testPath)
It should be
exists = fso.FileExists(testPath)
as you are looking for a file, not a folder.
The second problem is caused by your line
count + 1
It should be
count = count + 1
to assign the new/increased value to count.
Count is always starts at 1 because you say so. Count = 1. Store count in a file.