【发布时间】:2015-10-05 02:01:55
【问题描述】:
我有一个 VBA 脚本,用于从用户(以表格形式)获取产品名称、数量和价格的输入,如果一切都通过验证,那么它应该将其添加到列出产品的表格的底部.
除了检查数量和价格是否为数字的验证检查外,一切似乎都很好,它似乎总是通过这个检查。
任何帮助都会很棒。谢谢
我在下面复制了我的代码:
Dim strName As String
Dim intResponse, intQuantity, intProdNumber As Integer
Dim intPrice As Currency
Dim wksInventory As Worksheet
Dim wksRange As Range
'Define Variables
Set wksInventory = Application.ActiveWorkbook.Worksheets(2) 'Set to correct worksheet
wksInventory.Select
wksInventory.Columns("A:D").HorizontalAlignment = xlCenter
wksInventory.Range("A2").Select
intProdNumber = 1
strName = txtProduct.Text 'Assign strName to input in txtProduct text box
intQuantity = Val(txtQuantity.Text) 'Assign intQuantity to input in txtQuantity text box
intPrice = Val(txtPrice.Text) 'Assign intPrice to input in txtPrice text box
Do Until IsEmpty(ActiveCell)
If intProdNumber <= Val(ActiveCell.Value) Then
intProdNumber = Val(ActiveCell.Value) + 1
End If
ActiveCell.Offset(1, 0).Select
Loop
intResponse = MsgBox("Are you certain of the following:" + vbNewLine + "Product Name: " + strName + vbNewLine + "Quantity: " + CStr(intQuantity) + vbNewLine + "Price: " + CStr(intPrice), vbYesNo)
'Validating Product Name
If Not (Len(strName) = 0) Then 'Check that strName isn't empty
If Not (IsNumeric(strName)) Then 'Check that it is not a number
'Do Nothing - Maintain value of intResponse
Else
MsgBox ("Product Name should not be a number")
intResponse = 0 'Set intResponse to value different than vbYes
End If
Else
MsgBox ("Product Name is empty")
intResponse = 0 'Set intResponse to value different than vbYes
End If
'Validating Quantity
If (intResponse = 6) Then
If (IsNumeric(intQuantity)) Then
If (intQuantity > 0) Then
'Do Nothing
Else
MsgBox ("Quantity should be greater than zero")
intResponse = 0 'Set intResponse to value different than vbYes
End If
Else
MsgBox ("Quantity should be a number")
End If
End If
'Validating Price
If (intResponse = 6) Then
If (IsNumeric(intPrice)) Then
If (intPrice > 0) Then
'Do nothing
Else
MsgBox ("Price should be greater than zero")
intResponse = 0 'Set intResponse to value different than vbYes
End If
Else
MsgBox ("Price should be a number")
End If
End If
If intResponse = vbYes Then
ActiveCell.Value = intProdNumber
ActiveCell.Offset(0, 1) = txtProduct.Text
ActiveCell.Offset(0, 2) = CStr(intQuantity)
ActiveCell.Offset(0, 3) = "$" + CStr(Round(intPrice, 2))
txtProduct.Text = ""
txtQuantity.Text = ""
txtPrice.Text = ""
'Unload (frmNewProduct)
'frmInitial.Show
End If
【问题讨论】:
标签: vba validation excel numbers