PDA

View Full Version : Need help with select case structure



qpham26
02-12-2013, 12:43 PM
Hi guys, I am trying to do a simple program that tell if a number is divisible by 3 or 5
so if the number can only be divisible by 3 or 5 then it will return a msgbox saying " only divisible by ..."
if the number can divisble by both then msgbox "Divisible by 3 and 5"
if the number cannot divisble by both then msgbox "not Divisible by 3 and 5"

I was able to do this using if-else-then structure. But I have no idea how to use select case to do this.

Please help. Thanks a lot.
This is my work using if-else

Sub problem3()
Dim a As Double, b As Double, c As Double

Sheets("sheet3").Select
Range("b2").Select
a = ActiveCell.Value
b = a Mod 3
c = a Mod 5

If (b = 0 And c = 0) Then
MsgBox "Divisible by 3 and 5"
ElseIf (b = 0 And c <> 0) Then
MsgBox "Only divisible by 3"
ElseIf (c = 0 And b <> 0) Then
MsgBox "Only divisible by 5"
ElseIf (c <> 0 And b <> 0) Then
MsgBox "Not divisible by 3 and 5"
End If

End Sub

Kenneth Hobs
02-12-2013, 01:05 PM
Welcome to the forum!

Sub problem3()
Dim a As Double, b As Double, c As Double, r As Range

Set r = Worksheets("Sheet3").Range("B2")

r.Value = 15
a = r.Value
b = a Mod 3
c = a Mod 5

Select Case True
Case b = 0 And c = 0
MsgBox "Divisible by 3 and 5"
Case b = 0
MsgBox "Only divisible by 3"
Case c = 0
MsgBox "Only divisible by 5"
Case Else
MsgBox "Not divisible by 3 and 5"
End Select
End Sub

qpham26
02-12-2013, 01:11 PM
Thanks,
that does look nicer than what i have,
I had to use 3 select case to do this =)) lol

Sheets("Sheet4").Select

Dim a As Double, b As Double, c As Double
Dim d As Double, e As Double, f As Double

Range("C4").Select
a = ActiveCell.Value
b = a Mod 3
c = a Mod 5

Select Case b
Case 0: d = 0
Case Else: d = 1
End Select

Select Case c
Case 0: e = 0
Case Else: e = 2
End Select

f = d + e

Select Case f
Case 0
MsgBox "Divisible by 3 and 5"
Case 1
MsgBox "Only divisible by 5"
Case 2
MsgBox "Only divisible by 3"
Case 3
MsgBox "Not divisible by 3 and 5"
End Select


End Sub

snb
02-13-2013, 02:30 AM
Please do not quote !

or


Sub M_snb()
x=15
MsgBox "Is divisible by " & Choose(Abs((x Mod 3 = 0) + 2 * (x Mod 5 = 0)) + 1, "nor 3 nor 5", "3", "5", "3 and 5")
End Sub