I just started learning VB6 on my own. I have created a simple calculator and I would like it to display the "operator" on the screen.
For example, if I press "1", followed by "plus sign", then finally "8", I would like the calculator to show "1 + 8". And when the "equal" sign is pressed, the calculator should show "1 + 8 = 9".
Below is a very noob code I made:
Dim formula As String
Dim itemOne As Integer
Dim itemTwo As Integer
Private Sub btn1_Click()
txtboxScreen.Text = txtboxScreen.Text & 1
End Sub
Private Sub btn2_Click()
txtboxScreen.Text = txtboxScreen.Text & 2
End Sub
Private Sub btn3_Click()
txtboxScreen.Text = txtboxScreen.Text & 3
End Sub
Private Sub btn4_Click()
txtboxScreen.Text = txtboxScreen.Text & 4
End Sub
Private Sub btn5_Click()
txtboxScreen.Text = txtboxScreen.Text & 5
End Sub
Private Sub btn6_Click()
txtboxScreen.Text = txtboxScreen.Text & 6
End Sub
Private Sub btn7_Click()
txtboxScreen.Text = txtboxScreen.Text & 7
End Sub
Private Sub btn8_Click()
txtboxScreen.Text = txtboxScreen.Text & 8
End Sub
Private Sub btn9_Click()
txtboxScreen.Text = txtboxScreen.Text & 9
End Sub
Private Sub btnDivide_Click()
itemOne = txtboxScreen.Text
txtboxScreen.Text = ""
formula = "/"
End Sub
Private Sub btnEqual_Click()
itemTwo = txtboxScreen.Text
If formula = "+" Then
txtboxScreen.Text = itemOne + itemTwo
ElseIf formula = "-" Then
txtboxScreen.Text = itemOne - itemTwo
ElseIf formula = "*" Then
txtboxScreen.Text = itemOne * itemTwo
ElseIf formula = "/" Then
txtboxScreen.Text = itemOne / itemTwo
End If
End Sub
Private Sub btnMinus_Click()
itemOne = txtboxScreen.Text
txtboxScreen.Text = ""
formula = "-"
End Sub
Private Sub btnPlus_Click()
itemOne = txtboxScreen.Text
txtboxScreen.Text = ""
formula = "+"
End Sub
Private Sub btnTimes_Click()
itemOne = txtboxScreen.Text
txtboxScreen.Text = ""
formula = "*"
End Sub
Private Sub btnZero_Click()
txtboxScreen.Text = txtboxScreen.Text & 0
End Sub
You may want to think about using a control array for you number buttons. This will vastly simplify your code in this instance and especially for more complex projects:
Private formula As String
Private itemOne As Integer
Private itemTwo As Integer
Private Sub btnNumbers_Click(Index As Integer)
txtboxScreen.Text = txtboxScreen.Text & Index
End Sub
''Remainder of your code goes here
Also, when you are declaring variables in the Declaration section of the form you should use Private instead of Dim.
I think you would like to concatenate the operator sign of the pressed button with the value you had in the textbox on button_click event.
something like:
Private Sub btnPlus_Click()
txtboxScreen.Text = txtboxScreen.Text & " + "
End Sub
and on equal button, you'd like to evaluate the expression
Private Sub btnEqual_Click()
txtboxScreen.Text = txtboxScreen.Text & " = " & Eval(txtboxScreen.Text)
End Sub
evaluating using Eval() is not a robust solution, but it's a simple way to achive that functionality.
You should save your first number, second number and operator (you called it "formula") separately and handle setting the text of the text box separately. Here is one way to do it:
Dim formula As String
Dim itemOne As String 'This time this is string
Dim itemTwo As String 'This time this is string
Dim currentItem As String 'Will hold the current number being entered
Dim Result As String 'This is string, too.
All your buttons will have code like:
Private Sub btn1_Click()
currentItem = currentItem & "1"
UpdateText()
End Sub
The operator buttons:
Private Sub btnPlus_Click()
itemOne = currentItem
formula = "+"
UpdateText()
End Sub
And the Equals button:
Private Sub btnEqual_Click()
itemTwo = currentItem
If formula = "+" Then
'Str is optional, but Val's are necessary since
'itemOne and itemTwo are strings.
Result = Str( Val(itemOne) + Val(itemTwo) )
ElseIf ...
.
.
.
End If
UpdateText()
End Sub
Well, noticed the call to UpdateText() at the end of every subprocedure? Here it is:
Private Sub UpdateText()
txtboxScreen.Text = itemOne & formula & itemTwo
'If result is not empty, we will add the '=' part too
If Result <> "" Then
txtboxScreen.Text = txtboxScreen.Text & "=" & Result
End If
End Sub
You might also be interested in an AC/ON key which sets all the variables to "".
The method was not so neat, but it's the best thing you can do without an expression evaluator. An expression evaluator can calculate the entire formula as it is. Eval is such a function and you can find some implementations of it on the net.
Related
Here is the code which I have written in vb6...it is showing error in text1.setfocus
Private Sub Text1_Lostfocus()
s1 = Text1.Text
flag = 0
If Text1.Text = "" Then
flag = 1
End If
For i = 1 To Len(s1)
l = Mid(s1, i, 1)
If IsNumeric(l) = True Then
flag = 1
Exit For
End If
Next i
If flag = 1 Then
MsgBox "Enter valid input"
Text1.ForeColor = vbRed
Text1.SetFocus
End If
End Sub
Do not have this code in LostFocus, instead try to have it in the Validate event, there would be an cancel parameter to the event, if you set Cancel = True (means the cursor will not exit the control) you need not do setfocus
Try the following:
Private Sub Text1_Validate(Cancel As Boolean)
If IsNumeric(Text1.Text) = False Then
MsgBox "Enter valid input"
Text1.ForeColor = vbRed
Cancel = True
End If
End Sub
Try this if you have an empty string and you are trying to work with in in your loop you can get an invalid procedure call. skip over it all togehter don't run the loop if the text is empty.
Private Sub Text1_Lostfocus()
s1 = Text1.Text
flag = 0
If Text1.Text = "" Then
flag = 1
else
For i = 1 To Len(s1)
l = Mid(s1, i, 1)
If IsNumeric(l) = True Then
flag = 1
Exit For
End If
Next i
endif
If flag = 1 Then
MsgBox "Enter valid input"
Text1.ForeColor = vbRed
Text1.SetFocus
End If
End Sub
Private Sub Worksheet_Calculate()
Dim cell As Range
Set cell = Range("E9")
If IsNumeric(cell) Then
If cell.Value < 0 Then
ActiveSheet.Shapes("Rectangle 2").Fill.ForeColor.RGB = vbRed
Else
ActiveSheet.Shapes("Rectangle 2").Fill.ForeColor.RGB = vbGreen
End If
End If
End Sub
Hi, how can I expand this code to work with multiple shapes? I tried to just copy everything from Set cell to End if and changed up the Set cell value and shape but this didn't work.
Private Sub Worksheet_Calculate()
Dim x As Range
Set x = Range("E9")
If IsNumeric(x) Then
If x.Value < 0 Then
Sheets("DIA").Shapes("Rectangle 2").Fill.ForeColor.RGB = vbRed
Else
Sheets("DIA").Shapes("Rectangle 2").Fill.ForeColor.RGB = vbGreen
End If
End If
Dim y As Range
Set y = Range("T9")
If IsNumeric(y) Then
If y.Value < 0 Then
Sheets("DIA").Shapes("Rectangle 19").Fill.ForeColor.RGB = vbGreen
Else
Sheets("DIA").Shapes("Rectangle 19").Fill.ForeColor.RGB = vbRed
End If
End If
End Sub
This works, any smarter ways?
visual basic is saying something with too many argument to Public Sub CheckCollision? Help please
Public Class Form1
Dim intSpeedX As Integer = 2
Dim intSpeedY As Integer = -2
Dim intScore As Integer
Dim intLives As Integer = 3
Dim intAllGone As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
AllGone = 0
CheckCollisions()
If AllGone = 1 Then
Timer1.Enabled = False
MsgBox("You finished the game!", , "CONGRATULATIONS")
End If
BallX += SpeedX
If BallX < 3 Or BallX + Ball.Width > Me.Width - 5 Then
SpeedX = -SpeedX
End If
BallY += SpeedY
If BallY < 3 Then
SpeedY = -SpeedY
End If
If BallY + Ball.Height > Me.Height - 5 Then
Timer1.Enabled = False
UpdateLives()
BallX = 232
BallY = 376
SpeedX = 2
SpeedY = -2
If Lives < 1 Then
MsgBox("You have lost the game.", , "OH NAWW MAN DAT SUCKS!")
Else
MsgBox("You missed!", , "OH NOOOO")
Timer1.Enabled = True
End If
End If
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
Paddle.Left = e.X - Paddle.Width \ 2
End Sub
Public Sub CheckCollisions()
CheckCollision(Paddle, False) <---error here with the false
CheckCollision(Red1)
CheckCollision(Red2)
CheckCollision(Red3)
CheckCollision(Red4)
CheckCollision(Red5)
CheckCollision(Yellow1)
CheckCollision(Yellow2)
CheckCollision(Yellow3)
CheckCollision(Yellow4)
CheckCollision(Yellow5)
CheckCollision(Green1)
CheckCollision(Green2)
CheckCollision(Green3)
CheckCollision(Green4)
CheckCollision(Green5)
CheckCollision(Blue1)
CheckCollision(Blue2)
CheckCollision(Blue3)
CheckCollision(Blue4)
CheckCollision(Blue5)
End Sub
Public Sub CheckCollison(ByVal src As PictureBox, ByVal Hide As Boolean)
If src.Visible = True Then
If BallX > src.Location.X And _
BallX < src.Location.X + src.Size.Width And _
Ball.Location.Y > src.Location.Y And _
Ball.Location.Y < src.Location.Y + src.Size.Height Then
SpeedY = -SpeedY
UpdateScore()
If Hide Then
src.Visible = False
End If
End If
AllGone += 1
End If
End Sub
'declare the overloaded version of CheckCollision
Public Sub CheckCollision(ByVal src As PictureBox)
'call the original version
CheckCollision(src, True) <------error here
End Sub
Public Sub UpdateScore()
Score += 10
Label2.Text = "SCORE: " & Score
End Sub
Public Sub UpdateLives()
Lives -= 1
Label1.Text = "LIVES: " & Lives
End Sub
Public Property BallX() As Integer
Get
Return Ball.Left
End Get
Set(ByVal Value As Integer)
Ball.Left = Value
End Set
End Property
Public Property BallY() As Integer
Get
Return Ball.Top
End Get
Set(ByVal Value As Integer)
Ball.Top = Value
End Set
End Property
Public Property Lives() As Integer
Get
Return intLives
End Get
Set(ByVal Value As Integer)
intLives = Value
End Set
End Property
Public Property SpeedX() As Integer
Get
Return intSpeedX
End Get
Set(ByVal Value As Integer)
intSpeedX = Value
End Set
End Property
Public Property SpeedY() As Integer
Get
Return intSpeedY
End Get
Set(ByVal Value As Integer)
intSpeedY = Value
End Set
End Property
Public Property Score() As Integer
Get
Return intScore
End Get
Set(ByVal Value As Integer)
intScore = Value
End Set
End Property
Public Property AllGone() As Integer
Get
Return intAllGone
End Get
Set(ByVal Value As Integer)
intAllGone = Value
End Set
End Property
End Class
You owerite CheckCollision with:
Public Sub CheckCollision(ByVal src As PictureBox)
'call the original version
CheckCollision(src, True) <------error here
End Sub
which accepts only one argument, so
CheckCollision(src, True)
won't work, because it calls the overwritten sub.
Currently I am working on vb6 application. I want to show data in MSFlexgrid But there is no edit Facility in MSFlexgrid Control.
Is there Any way to Edit MSFlexgrid?
There is a way using hidden Textbox. On the double click on the cell the textbox will be visible and Edit is possible here is code snippet check it
Private Sub Form_Load()
'Setting Col And row
MSFlexGrid1.Cols = 3
MSFlexGrid1.Rows = 10
'First row
MSFlexGrid1.TextMatrix(0, 0) = "ID"
MSFlexGrid1.TextMatrix(0, 1) = "Date"
MSFlexGrid1.TextMatrix(0, 2) = "Voucher Type"
'some data
MSFlexGrid1.TextMatrix(1, 0) = "E0000001"
MSFlexGrid1.TextMatrix(2, 0) = "E0000001"
MSFlexGrid1.TextMatrix(1, 1) = "01/04/10"
MSFlexGrid1.TextMatrix(2, 1) = "01/04/10"
MSFlexGrid1.TextMatrix(1, 2) = "Jrnl"
MSFlexGrid1.TextMatrix(2, 2) = "Jrnl"
End Sub
Private Sub MSFlexGrid1_DblClick()
'If MSFlexGrid1.Col = 3 Or MSFlexGrid1.Col = 6 Or MSFlexGrid1.Col = 7 Then
GridEdit Asc(" ")
'End If
End Sub
Private Sub MSFlexGrid1_KeyPress(KeyAscii As Integer)
GridEdit KeyAscii
End Sub
Sub GridEdit(KeyAscii As Integer)
'use correct font
Text1.FontName = MSFlexGrid1.FontName
Text1.FontSize = MSFlexGrid1.FontSize
Select Case KeyAscii
Case 0 To Asc(" ")
Text1 = MSFlexGrid1
Text1.text = Trim(Text1.text)
Text1.SelStart = 1000
Case Else
Text1 = MSFlexGrid1
Text1.text = Trim(Text1.text)
Text1.SelStart = 1000
End Select
'position the edit box
Text1.Left = MSFlexGrid1.CellLeft + MSFlexGrid1.Left
Text1.Top = MSFlexGrid1.CellTop + MSFlexGrid1.Top
Text1.Width = MSFlexGrid1.CellWidth
Text1.Height = MSFlexGrid1.CellHeight
Text1.Visible = True
Text1.SetFocus
End Sub
Private Sub MSFlexGrid1_LeaveCell()
If Text1.Visible Then
If MSFlexGrid1.Col = 6 Or MSFlexGrid1.Col = 7 Then
If Text1.text = "" Then
Text1.text = " "
End If
End If
MSFlexGrid1 = Text1
Text1.Visible = False
End If
End Sub
Private Sub MSFlexGrid1_GotFocus()
If Text1.Visible Then
If MSFlexGrid1.Col = 6 Or MSFlexGrid1.Col = 7 Then
If Text1.text = "" Then
Text1.text = " "
End If
End If
MSFlexGrid1 = Text1.text
Text1.Visible = False
End If
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
'noise suppression
If MSFlexGrid1.Col <> 6 And MSFlexGrid1.Col <> 7 Then
KeyAscii = 0
End If
If KeyAscii = vbKeyReturn Then
KeyAscii = 0
End If
End Sub
Can you also try below code. This doesnt require text box.
'Put this code in MSFlexGrid Keypress Event
'===================================================
Private Sub MSFlexGrid_KeyPress(KeyAscii As Integer)
With MSFlexGrid
Select Case KeyAscii
Case 8: 'IF KEY IS BACKSPACE THEN
If .Text <> "" Then .Text = _
Left$(.Text, (Len(.Text) - 1))
Case 13: 'IF KEY IS ENTER THEN
Select Case .Col
Case Is < (.Cols - 1):
SendKeys "{right}"
Case (.Cols - 1):
If (.Row + 1) = .Rows Then
.Rows = .Rows + 1
End If
SendKeys "{home}" + "{down}"
End Select
Case Else
.Text = .Text + Chr$(KeyAscii)
'write your own keyascii Validations under
'commented lines
Select Case .Col
Case 0, 1, 2:
'if (your condition(s)) then
'accept only charectors
'Else
' keyascii=0
'End If
Case Else:
End Select
End Select
End With
End Sub
I was trying this script from a pdf file.I got stuck where the target image should change to exploding image if clicked but the target image does not change from the standing image.Please Help!
Option Explicit
Dim fiPlayersScore As Integer
Dim fiNumberofMisses As Integer
Dim fbTargetHit As Boolean
Private Sub Form_Load()
Randomize
imgTarget.Enabled = False
imgTarget.Visible = False
cmdStop.Enabled = False
lblGameOver.Visible = False
lblGameOver.Enabled = False
End Sub
Private Sub cmdStart_Click()
Dim lsUserResponse As String
Dim lbResponse As Boolean
lsUserResponse = InputBox("Enter a level from 1 to 3." & _
(Chr(13)) & "" & (Chr(13)) & "1 being the Easiest and 3 being the " & _
"Hardest.", "Level Select", "1")
lbResponse = False
If lsUserResponse = "1" Then
Timer1.Interval = 1500
lbResponse = True
ElseIf lsUserResponse = "2" Then
Timer1.Interval = 1000
lbResponse = True
ElseIf lsUserResponse = "3" Then
Timer1.Interval = 750
lbResponse = True
Else
MsgBox ("Game Not Started.")
lbResponse = False
End If
If lbResponse = True Then
cmdStart.Enabled = False
imgTarget.Picture = imgStanding.Picture
frmMain.MousePointer = 5
fbTargetHit = False
Load_Sounds
cmdStop.Enabled = True
fiPlayersScore = 0
fiNumberofMisses = 0
lblScore.Caption = fiPlayersScore
lblMisses.Caption = fiNumberofMisses
Timer1.Enabled = True
lblGameOver.Visible = False
lblGameOver.Enabled = False
End If
End Sub
Private Sub cmdStop_Click()
Unload_Sounds
frmMain.MousePointer = vbNormal
Timer1.Enabled = False
imgTarget.Enabled = False
imgTarget.Visible = False
cmdStart.Enabled = True
cmdStop.Enabled = False
cmdStart.SetFocus
lblGameOver.Visible = True
lblGameOver.Enabled = True
End Sub
Private Sub Form_Click()
MMControl1.Command = "Play"
MMControl1.Command = "Prev"
fiNumberofMisses = fiNumberofMisses + 1
lblMisses.Caption = fiNumberofMisses
If CheckForLoose = True Then
cmdStop_Click
lblMisses.Caption = fiNumberofMisses
Exit Sub
End If
End Sub
Private Sub imgTarget_Click()
MMControl2.Command = "Play"
MMControl2.Command = "Prev"
Timer1.Enabled = False
imgTarget.Picture = imgExplode.Picture '**I AM STUCK HERE**
pauseProgram
fiPlayersScore = fiPlayersScore + 1
Timer1.Enabled = True
If CheckForWin = True Then
cmdStop_Click
lblScore.Caption = fiPlayersScore
Exit Sub
End If
lblScore.Caption = fiPlayersScore
fbTargetHit = True
imgStanding.Enabled = False
imgTarget.Visible = False
imgTarget.Enabled = False
Timer1.Enabled = True
End Sub
Public Sub Load_Sounds()
'Set initial property values for blaster sound
MMControl1.Notify = False
MMControl1.Wait = True
MMControl1.Shareable = False
MMControl1.DeviceType = "WaveAudio"
MMControl1.FileName = _
"C:\Temp\Sounds\Blaster_1.wav"
'Open the media device
MMControl1.Command = "Open"
Private Sub Timer1_Timer()
Dim liRandomLeft As Integer
Dim liRandomTop As Integer
imgTarget.Visible = True
If fbTargetHit = True Then
fbTargetHit = False
imgTarget.Picture = imgStanding.Picture
End If
liRandomLeft = (6120 * Rnd)
liRandomTop = (4680 * Rnd)
imgTarget.Left = liRandomLeft
imgTarget.Top = liRandomTop
imgTarget.Enabled = True
imgTarget.Visible = True
End Sub
Public Function CheckForWin() As Boolean
CheckForWin = False
If fiPlayersScore = 5 Then
CheckForWin = True
lblGameOver.Caption = "You Win.Game Over"
End If
End Function
Public Function CheckForLoose() As Boolean
CheckForLoose = False
If fiNumberofMisses = 5 Then
CheckForLoose = True
lblGameOver.Caption = "You Loose.Game Over"
End If
End Function
Private Sub Form_QueryUnload(Cancel As Integer, _
UnloadMode As Integer)
Unload_Sounds
End Sub
Public Sub Unload_Sounds()
MMControl1.Command = "Close"
MMControl2.Command = "Close"
End Sub
Public Sub pauseProgram()
Dim currentTime
Dim newTime
currentTime = Second(Time)
newTime = Second(Time)
Do Until Abs(newTime - currentTime) >= 1
newTime = Second(Time)
Loop
End Sub
EDIT:
imgTarget.Picture = imgExplode.Picture
imgTarget.Refresh
Note:
Set imgTarget.Picture = imgExplode.Picture
imgTarget.Refresh
will be faster than
imgTarget.Picture = imgExplode.Picture
imgTarget.Refresh
if imgExplode is going to be around during the lifetime of imgTarget (the first command copies the image, the Set command references the image).