Newbie visual basic 6 - vb6

Private Sub Command1_Click()
Select Case used.Text
Case Is <= 30
pay = used * 120
Case Is > 30, Is <= 60
pay = used * 150
Case Is > 60, Is <= 90
pay = used * 190
End Select
EX:
MR.A used 75m3 of water a month so he must pay:
30 x 120 = 3600
30 x 150 = 4500
15 x 15 = 2850
and total : 10950
but my code doesnt right help me fix it im newbie

i'm also a newbie, sure this is a horrible way to code it but it seems to work...first off replace literals with variables to allow for changing requirements. I didn't check many cases so this might not be exact but was fun to think thru the problem.
Private Sub Command1_Click()
Dim pay As Double
Dim used As Double
Dim balance As Double
Dim BillingIncrement As Double
Dim FirstUnitPrice As Double
Dim SecondUnitPrice As Double
Dim MaxUnitPrice As Double
BillingIncrement = 30
FirstUnitPrice = 120
SecondUnitPrice = 150
MaxUnitPrice = 190
'put in loop to test various inputs for debug only
For used = 10 To 100 Step 5
Debug.Print "used ", used
If used <= BillingIncrement Then
pay = used * FirstUnitPrice
Else
pay = BillingIncrement * FirstUnitPrice
Debug.Print "first " & BillingIncrement & " units billed at 120"
balance = used - BillingIncrement
Debug.Print "balance ", balance
If balance > BillingIncrement Then
pay = pay + BillingIncrement * SecondUnitPrice
Debug.Print "second " & BillingIncrement & " units billed at " & SecondUnitPrice
balance = balance - BillingIncrement
If balance > 0 Then
pay = pay + balance * MaxUnitPrice
Debug.Print balance, " units billed at " & MaxUnitPrice
End If
Else
Debug.Print balance, " billed at " & SecondUnitPrice
pay = pay + balance * SecondUnitPrice
End If
End If
Debug.Print "Pay = ", pay
' a couple example test cases
If used = 40 Then
If pay <> 5100 Then
Debug.Print "error"
Else: Debug.Print "ok so far"
End If
End If
If used = 60 Then
If pay <> 8100 Then
Debug.Print "error"
Else: Debug.Print "ok so far"
End If
End If
'reset for next loop
pay = 0
balance = 0
Next
End Sub

Related

Access VBA slow after first run

I have a general question. I think it is not code related.
I have a small access program using forms, SQL and VBA.
The VBA mainly calculate pretty simple things, but with a lot of data and some SQL runs. I have a status bar where i can see "percentage done".
I start the script by clearing all tables and after that running all queries to make sure they're empty.
I then run through the data. It works good.
It takes around 2 mins.
I then do it again.
But now it takes 10 mins. For the same procedure.
If i restart access, it takes 2 mins the first time, then 10 mins afterwards.
When i restart access, the tables are still filled. So it is not because they are empty.
Is there a command to clear all memory or whatever might be needed?
Any suggestions?
The code that runs 10x slower:
For counter = 1 To n_bins
Application.Echo False
DoCmd.OpenQuery "q_PowerBinned"
If DCount("*", "q_PowerBinned") = 0 Then
DoCmd.OpenQuery "q_000"
DoCmd.RunSQL "DELETE * FROM q_000"
DoCmd.Close
strTMP = (counter - 1) * [Forms]![f_main]![PowerBinCombo] & " - " & counter * [Forms]![f_main]![PowerBinCombo] & " kW"
strSQL = "INSERT INTO q_000 (Bin, Zero1, Zero2, Zero3, Zero4, Zero5) VALUES ('" & strTMP & "','0','0','0','0','0');"
DoCmd.RunSQL strSQL
DoCmd.OpenQuery "q_Move000"
DoCmd.Close
Else
DoCmd.Close
End If
DoCmd.OpenQuery "q_Average_Temp"
DoCmd.Close
DoCmd.OpenQuery "q_MoveAverage"
DoCmd.OpenQuery "q_PowerBinned_VG"
If DCount("*", "q_PowerBinned_VG") = 0 Then
DoCmd.OpenQuery "q_000_VG"
DoCmd.RunSQL "DELETE * FROM q_000_VG"
DoCmd.Close
strTMP = (counter - 1) * [Forms]![f_main]![PowerBinCombo] & " - " & counter * [Forms]![f_main]![PowerBinCombo] & " kW"
strSQL = "INSERT INTO q_000_VG (Bin, Zero1, Zero2, Zero3, Zero4, Zero5) VALUES ('" & strTMP & "','0','0','0','0','0');"
DoCmd.RunSQL strSQL
DoCmd.OpenQuery "q_Move000_VG"
DoCmd.Close
Else
DoCmd.Close
End If
DoCmd.OpenQuery "q_Average_Temp_VG"
DoCmd.Close
DoCmd.OpenQuery "q_MoveAverage_VG"
Application.Echo True
' Theoretical of Measured Power Curve
Percentage = ((counter) / (n_bins)) * 100
strStatus = "Binned " & Percentage & " %"
Call dsp_progress_AfterUpdate
Me.Refresh
dsp_progress.SetFocus
dsp_progress.SelStart = 0
dsp_progress.SelLength = 0
DoEvents
Next counter
This happens for one of my access databases. I find that if I do a compact & repair after the appropriate tables have been emptied, the vba run-time returns to the short time again. Not the most elegant of solutions I must admit.

VB6 ProgressBar not working?

Inserted my progress bar and it didn't work as expected. When i logged in, it works, but it doesn't automatically loads the second form.
Here is my code for progress/timer
Private Sub Timer1_Timer()
If ProgressBar1.Value = 100 Then
ProgressBar1.Value = 0
Else
ProgressBar1.Value = Val(ProgressBar1.Value) + Val(20)
End If
Label3.Caption = ProgressBar1.Value
Label , to detect 100, variable prg to hold
Private Sub Label3_Change()
If (Label3.Caption = 100) Then
prg = 1
Timer1.Interval = 0
End If
End Sub
log in button
Private Sub cmdSign_Click()
currentTime = TimeValue(Now)
strCurrdate = Format(Date, "mmm d, YYYY")
rx.Open "Select * from login where username ='" & Text1 & "' and password='" & Text2 & "'", db, 3, 3
If (counter = 3) And (rx.EOF = True) Then
MsgBox "You guessed too many times! Intruder alert!"
End
Else
If rx.EOF = True Then
MsgBox "Invalid Username or Password"
counter = counter + 1
Text1 = ""
Text2 = ""
Else
user1 = Text1.Text
logTime = currentTime
rxd.Open "Select * from logHistory", db, 3, 3
With rxd
.AddNew
.Fields("username") = user1
.Fields("TimeDate") = strCurrdate
.Fields("TimeIn") = logTime
.Update
End With
Set rxd = Nothing
'problem might be here
ProgressBar1.Visible = True
Timer1.Interval = 100
Label3.Visible = True
Timer1.Enabled = True
If prg = 1 Then
MsgBox "Welcome " + Text1 + " to SPARTAN!"
mainmenu.Show
End If
End If
End If
Set rx = Nothing
End Sub
Any help on this?
Once the timer is started it runs asynchronously to the rest of your code. The way you have coded your login button you are expecting the timer to move the progressbar from 0 to 100, set your (I assume) module scoped variable prg to 1 and then continue. In reality your code enables the timer and moves on. When it reaches the If prg = 1 Then statement prg is still whatever it has been initialized at. One way to fix it is to check the prg variable in your timer event.
Private Sub Timer1_Timer()
If ProgressBar1.Value = 100 Then
Timer1.Enabled = False ' don't fire the timer event again
ProgressBar1.Value = 0
MsgBox "Welcome " & Text1 & " to SPARTAN!"
mainmenu.Show
Else
ProgressBar1.Value = Val(ProgressBar1.Value) + Val(20)
End If
Label3.Caption = ProgressBar1.Value
End Sub
I also changed your string concatenation + to &. The plus symbol "+" works, but is only included in VB versions after 3 for backward compatibility and it is considered bad form to use it for other than arithmetic. In VB version 4 and greater the ampersand "&" should be used for concatenation. MSDN reference here

VB6 expected end of statement

I can't figure out what I'm doing wrong. I keep getting the error "Expected: end of statement" under the 'Display output. comment.
Option Explicit
Private Sub cmdOkay_click()
'Declare counter variable (p)
Dim p As Integer
p = 8
'Declare variable to hold calculated minutes
Dim minutes As Integer
'Display title of chart in listbox
MyListBox.AddItem “Cooking Chart”
'For each pound (from 8 to 23), calculate and display minutes
For p = 8 To 23
'Calculate minutes.pounds * 17
minutes = p * 17
'Display output.
MyListBox.AddItem p & “ lbs, “ & minutes & “ minutes.” ERROR
Next p
End Sub
Private Sub cmdExit_Click()
End
End Sub
Your code didn't run because of the double quotes. I changed them and it ran without error
Copy and paste this code:
'Declare counter variable (p)
Dim p As Integer
p = 8
'Declare variable to hold calculated minutes
Dim minutes As Integer
'Display title of chart in listbox
MyListBox.AddItem "Cooking Chart"
'For each pound (from 8 to 23), calculate and display minutes
For p = 8 To 23
'Calculate minutes.pounds * 17
minutes = p * 17
'Display output.
MyListBox.AddItem p & " lbs, " & minutes & " minutes."
Next p

How to extract and manipulate data from text file in VB 2010 using string manipulation methods

I need help on extracting data from a specific text file (C:\test.txt). Text file contains student names and scores:
Alice,76,45,87,23
Ben,76,48,85,65
Julie,76,36,49,86
Monica,85,90,83,76
Given the grade structure which is: A (70-100), B(60-69),C(50-59),D(40-49),F(0-39)
Application should calculate the average score and grade received by each student
Display who received the highest mark
Display the average mark of all students in the class
List students who received grade "C"
The required methods to be used are Len, Mid and Instr
File to be processed line by line
Many thanks for the help!
It can provably be tidied up because i just knocked it out.
To test it drop a multiline TEXTBOX (named textbox1) and a Button (named button1) on a form and click the button.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'-> Data
' Alice, 76, 45, 87, 23
' Ben, 76, 48, 85, 65
' Julie, 76, 36, 49, 86
' Monica, 85, 90, 83, 76
'-> Variables
Dim strTextLine As String
Dim intCounter As Integer
Dim chrCurrentCharacter As String
Dim strBuffer As String
Dim strResults As String
Dim booNameFound As Boolean
'-> Processing
'1 calculate the average score and grade received by each student
Dim intIndividualAverage As Integer = 0
'2 Display who received the highest mark
Dim intHighest As Integer = 0
Dim intTmpHighest As Integer = 0
Dim strHighest As String = ""
'3 Display the average mark of all students in the class
Dim intGroupAverage As Integer = 0
'4 List students who received grade "C"
Dim strGradeCStudents = ""
Dim strName As String = ""
'-> Grading Rules
' A (70-100), B(60-69),C(50-59),D(40-49),F(0-39)
'-> Open file and process data one line at a time
Try
' Create an instance of StreamReader to read from a file
Dim objStreamReader As StreamReader = New StreamReader("c:\temp\test.txt")
' Read the lines from the file until the end of the file is reached.
Do
strTextLine = objStreamReader.ReadLine()
'if not eof or empty text line
If Trim(strTextLine) <> "" Then
'reset vars
strName = ""
strBuffer = ""
strResults = ""
booNameFound = False
intIndividualAverage = 0
For intCounter = 1 To Len(strTextLine)
chrCurrentCharacter = Mid(strTextLine, intCounter, 1)
'is this a comma?
If chrCurrentCharacter = "," Then
'has the name been found?
If booNameFound Then
'this is a grade result(note there is no Grade E!)
Select Case Val(strBuffer)
Case 70 To 100
strResults = strResults & " A"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
intGroupAverage = intGroupAverage + Val(strBuffer)
Case 60 To 69
strResults = strResults & " B"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
intGroupAverage = intGroupAverage + Val(strBuffer)
Case 50 To 59
strResults = strResults & " C"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
intGroupAverage = intGroupAverage + Val(strBuffer)
'grade C Students
If InStr(strGradeCStudents, strName) > 0 Then
'alreadylisted inthe grade c list
Else
strGradeCStudents = strGradeCStudents & strName & " "
End If
Case 40 To 49
strResults = strResults & " D"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
intGroupAverage = intGroupAverage + Val(strBuffer)
Case Else
strResults = strResults & " F"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
intGroupAverage = intGroupAverage + Val(strBuffer)
End Select
strBuffer = ""
Else
'this is name
booNameFound = True
strResults = strBuffer
strName = strBuffer
strBuffer = ""
End If
'if its not a space
ElseIf chrCurrentCharacter <> " " Then
strBuffer = strBuffer & chrCurrentCharacter
Else
'Spaces are not processed
End If
Next
'Process LAST result because there is no comma after it
'so it must be done after the endof the line
Select Case Val(strBuffer)
Case 70 To 100
strResults = strResults & " A"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
Case 60 To 69
strResults = strResults & " B"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
Case 50 To 59
strResults = strResults & " C"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
Case 40 To 49
strResults = strResults & " D"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
Case Else
strResults = strResults & " F"
intIndividualAverage = intIndividualAverage + Val(strBuffer)
End Select
strBuffer = ""
'Student average
strResults = strResults & " (avg=" & (intIndividualAverage / 4) & ")" & vbCrLf & vbCrLf
TextBox1.Text = TextBox1.Text & strResults
'Console.WriteLine(strResults)
'Highest?
If intHighest = 0 Then
strHighest = strName
ElseIf intTmpHighest > intHighest Then
strHighest = strName
ElseIf intTmpHighest = intHighest Then
strHighest = strHighest & " " & strName
End If
Else
'The line was empty
End If
Loop Until strTextLine Is Nothing
objStreamReader.Close()
'-> Display Summary
TextBox1.Text = TextBox1.Text & vbCrLf & "SUMMARY" & vbCrLf
TextBox1.Text = TextBox1.Text & "Highest Marks: " & strHighest & vbCrLf
TextBox1.Text = TextBox1.Text & "Group Average: " & ((intGroupAverage / 4) / 4) & vbCrLf
TextBox1.Text = TextBox1.Text & "Grade C Students: " & strGradeCStudents & vbCrLf
Catch Ex As Exception
' Let the user know what went wrong.
TextBox1.Text = TextBox1.Text & "The file could not be read:"
TextBox1.Text = TextBox1.Text & Ex.Message
'Console.WriteLine("The file could not be read:")
'Console.WriteLine(Ex.Message)
End Try
End Sub

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