【问题标题】:Filtering out the percent symbol过滤掉百分比符号
【发布时间】:2014-04-08 13:34:45
【问题描述】:

我使用的是 Excel 2010,我有一些代码会提示用户输入百分比,然后将单元格 A1 中的值增加该百分比。如果有人遵守规则并输入一个整数作为百分比,它就可以正常工作。因此,例如,如果有人希望值增加 30%,他们会在输入框中输入 30。

如果有人在他们的回复中添加一个百分比符号,它会破坏整个事情。如何修改此代码,使其捕获百分比符号并仅根据整数进行计算。谢谢。

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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您可以使用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"))
    

    【讨论】:

    • 确实很聪明。
    【解决方案2】:

    非正则表达式解决方案:)

    Sub box()
    
    Dim mypercent
    
    mypercent = InputBox("How much of an increase")
    If mypercent Like "*[0-9]" Then
        Range("A1").Value = Range("A1").Value * (1 + (myPercent * 0.01))
    Else
        MsgBox "Not valid input. Enter whole numbers only"
    End If
    
    End Sub
    

    【讨论】:

      【解决方案3】:

      也试试这个代码:

      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))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多