Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

excel - EXtracting number in VBA while using IF - REFRESH

I want to extract a number in a String and apply this number to the IF function, but if the source row changes the If function that contains the VBA function does NOT refresh.

Exemple> Source row= 10VBA

Public Function JustNumber(ByVal vValor As String) As String
   Application.Volatile True
    
    Dim vQtdeCaract As Long
    Dim vControle   As Boolean
    
    vQtdeCaract = Len(vValor)
    vControle = False
    
    For i = 1 To vQtdeCaract
        
        If IsNumeric(Mid(vValor, i, 1)) Then
            If vControle = True And JustNumber <> vbNullString Then
                JustNumber = JustNumber + "/"
            End If
            vControle = False
            JustNumber = JustNumber & Mid(vValor, i, 1)
        Else
            vControle = True
        End If
    Next
End Function

returns the number 10

=IF(JustNumber(source row)=10;"True";"False")

Returns "True"

But, if I change the source row the IF fuction doesn't change, there is a way to refresh the function after the change in the Source row to 15VBA, making the function = "False" ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some suggestions:

  • Name your procedures and variables to something meaningful
  • Use Option Explicit at the top of your modules

Some adjustments:

  • You're getting a string from the function result (you either can change the function result or evaluate the number as string in the Excel formula)
  • I simplified the loop to extract the numbers

Code:

Public Function numbersFromString(ByVal evalString As String) As Double

    Application.Volatile True
    
    ' Get string length
    Dim stringLength As Integer
    stringLength = Len(evalString)
    
    ' Loop through characters in string and extract numbers
    Dim resultString As String
    Dim counter As Long
    For counter = 1 To stringLength
        If IsNumeric(Mid(evalString, counter, 1)) Then resultString = resultString & Mid(evalString, counter, 1)
    Next counter
    
    ' Check if there are any numbers
    If Len(resultString) > 0 Then
        ' Convert to number
        numbersFromString = CDbl(resultString)
    End If

End Function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...