Excel 过滤掉百分比符号
我正在使用Excel 2010,我有一些代码提示用户输入一个百分比,然后将单元格A1中的值增加该百分比。如果有人按照规则玩游戏,并键入一个整数作为百分比,它就可以正常工作。例如,如果有人希望值增加30%,他们会在输入框中键入30 如果有人在他们的回复中添加了一个百分比符号,这会破坏整个事情。如何修改此代码,使其捕获百分比符号并仅基于整数进行计算。多谢各位Excel 过滤掉百分比符号,excel,vba,Excel,Vba,我正在使用Excel 2010,我有一些代码提示用户输入一个百分比,然后将单元格A1中的值增加该百分比。如果有人按照规则玩游戏,并键入一个整数作为百分比,它就可以正常工作。例如,如果有人希望值增加30%,他们会在输入框中键入30 如果有人在他们的回复中添加了一个百分比符号,这会破坏整个事情。如何修改此代码,使其捕获百分比符号并仅基于整数进行计算。多谢各位 Sub Box1() Dim myPercent As Integer myPercent = InputBox("How m
Sub Box1()
Dim myPercent As Integer
myPercent = InputBox("How much of an increase?", "Input without the percent symbol")
Range("A1").Value = Range("A1").Value * (1 + (myPercent * 0.01))
End Sub
您可以使用
Replace
功能去除任何百分比符号:
myPercent = Replace(InputBox("How much of an increase?", "Input without the percent symbol"), "%", "")
或者,您可以使用Val
函数忽略第一个非数字字符后的所有内容:
myPercent = Val(InputBox("How much of an increase?", "Input without the percent symbol"))
非正则表达式解决方案:)
还可以尝试以下代码:
Dim myPercent
Do
myPercent = InputBox("How much of an increase?", "Input without the percent symbol")
If Not IsNumeric(myPercent) Then MsgBox "Wrong input! Try again.."
Loop Until IsNumeric(myPercent)
Range("A1").Value = Range("A1").Value * (1 + (myPercent * 0.01))
这的确是个聪明的办法。
Dim myPercent
Do
myPercent = InputBox("How much of an increase?", "Input without the percent symbol")
If Not IsNumeric(myPercent) Then MsgBox "Wrong input! Try again.."
Loop Until IsNumeric(myPercent)
Range("A1").Value = Range("A1").Value * (1 + (myPercent * 0.01))