VBA IF Then语句使用字符串变量

时间:2016-03-01 03:54:53

标签: vba excel-vba if-statement excel

我正在为我的编程课解决问题,并想知道我是否能得到一些帮助。下面的代码应该可以获得10%折扣的特定型号(AX1和SD2)的折扣。所有其他输入的折扣均为5%。现在代码发生的事情只是一个带有原始输入价格的扁平消息框。

Private Sub DiscountCalc_Click()

Dim strModelNum As String
Dim curOrigPrice As Currency
Dim sngRate As Long
Dim curDiscount As Long
Dim curNewPrice As Currency


strModelNum = InputBox("Enter desired model number", "Price Lookup")
strModelNum = UCase(strModelNum)

curOrigPrice = InputBox("Enter the original Price", "Price Lookup")
sngRate = 0.1
curDiscount = 0.05


If strModelNum = "AX1" Then
  curNewPrice = curOrigPrice - (curOrigPrice * sngRate)
Else If strModelNum = "SD2" Then
  curNewPrice = curOrigPrice - (curOrigPrice * sngRate)
Else
    curNewPrice = curOrigPrice - (curOrigPrice * curDiscount)
End If

   MsgBox curNewPrice

End Sub

3 个答案:

答案 0 :(得分:1)

尝试:

If strModelNum = "AX1" Or strModelNum = "SD2" Then
    curNewPrice = curOrigPrice - (curOrigPrice * sngRate)
Else
    curNewPrice = curOrigPrice - (curOrigPrice * curDiscount)
End If

答案 1 :(得分:1)

试试这段代码。

您需要将Long更改为Double。您也可以稍微压缩您的IF语句。

Private Sub DiscountCalc_Click()

Dim strModelNum As String
Dim curOrigPrice As Double
Dim sngRate As Double
Dim curDiscount As Double
Dim curNewPrice As Double


strModelNum = InputBox("Enter desired model number", "Price Lookup")
strModelNum = UCase(strModelNum)

curOrigPrice = InputBox("Enter the original Price", "Price Lookup")
sngRate = 0.1
curDiscount = 0.05


If strModelNum = "AX1" Or strModelNum = "SD2" Then
  curNewPrice = curOrigPrice - (curOrigPrice * sngRate)
Else
    curNewPrice = curOrigPrice - (curOrigPrice * curDiscount)
End If

   MsgBox curNewPrice

End Sub

答案 2 :(得分:1)

让我们看看这里:

Dim strModelNum As String
Dim curOrigPrice As Currency
Dim sngRate As Long
Dim curDiscount As Long
Dim curNewPrice As Currency

通过使用多头折扣率,我认为你在寻找麻烦。

Dim strModelNum As String
Dim curOrigPrice As Currency
Dim sngRate As Double
Dim curDiscount As Double
Dim curNewPrice As Currency