PDA

View Full Version : need help with coding

joacal
01-09-2009, 07:12 AM
OFFICE ENTERPRISE 2007

Dim bookcode, k, i, bookQty As Integer
Dim Booktitle As String
Dim bookprice, totalprice As Currency
For k = 1 To 5 Step 1
MsgBox "Book code " & Cells(k + 2, 2) & ", Book Title is " & Cells(k + 2, 3)
Next k
bookQty = InputBox("Input book quantity: ")
bookcode = InputBox("Enter book code: ")
For i = 1 To 5 Step 1
If bookcode = i Then
bookprice = Val(Cells(i + 2, 4))
Booktitle = Cells(i + 2, 3)
totalprice = bookQty * bookprice
Else
MsgBox "No such book."
Exit For
End If
MsgBox "Book Quantity is " & bookQty & ", Book title is " & Booktitle & ", Total Price is \$" & totalprice
Next i

MsgBox "Program End"
End Sub

I'm wondering why is it that it doesnt fall through the If statement when i input 1 as bookcode? I believe my spreadsheet has nothing wrong.. I always get the "no such book" statement.

Edit Lucas: vba tags added to code.

lucas
01-09-2009, 07:38 AM
Hi joacal,
Welcome to the forum.
It would help if you could provide some dummy data so we can see what you are encountering......

ps when posting code, select the code and hit the vba button to format it for the forum.

You can attach your workbook by hitting post reply at the bottom left of the last post and then aften entering your message, scroll down and look for a button that says "manage attachments"

Artik
01-09-2009, 07:40 AM
Dim bookcode As Long, k As Long, i As Long
Dim bookQty As Integer
Dim Booktitle As String
Dim bookprice As Currency, totalprice As Currency
Dim IsBookExist As Boolean

For k = 1 To 5 Step 1
MsgBox "Book code: " & Cells(k + 2, 2) & vbCr & _
"Book Title is: " & Cells(k + 2, 3)
Next k

bookQty = InputBox("Input book quantity: ")
bookcode = InputBox("Enter book code: ")
IsBookExist = False

For i = 1 To 5
If bookcode = i Then
IsBookExist = True
Exit For
End If
Next i

If IsBookExist Then
bookprice = Val(Cells(i + 2, 4))
Booktitle = Cells(i + 2, 3)
totalprice = bookQty * bookprice
MsgBox "Book Quantity is " & bookQty & vbCr & _
"Book title is " & Booktitle & vbCr & _
"Total Price is \$" & totalprice
Else
MsgBox "No such book."
End If

MsgBox "Program End"
End Sub
When you declare a few variables on the same line, you use As Type for each variable. Otherwise only the last type is specified, the rest are Variant.

Artik

Bob Phillips
01-09-2009, 07:53 AM
Is it because you are testing bookcode against i not 1?

joacal
01-09-2009, 08:04 AM
Thanks alot for the help. I manage to solve my problem.

Bob Phillips
01-09-2009, 08:39 AM
For the records, how did you solve it?

joacal
01-09-2009, 08:45 AM
Its the problem with my declarations..
I should have Dim every single variable..

or using Val(bookcode)
I was able to compare as well