Home > Enterprise >  Excel - Using IF and OR
Excel - Using IF and OR

Time:03-30

![enter image description here

Here is my code as text:

 Function NurZahl(ByVal Text As String) As Long
    Dim i%, tmp
    Dim Val As String
    
    For i = 1 To Len(Text)
      Val = Mid(Text, i, 1)
        If(OR(IsNumeric(Val),Val=","),TRUE, FALSE) Then tmp = tmp & Mid(Text, i, 1)
    Next i
    NurZahl = tmp
End Function

Complete Beginner here:

  • What is my problem with the if?
  • Is there a possibility to show me the exact problem in excel?
  • The text is only highlighted with red color - if i hover with the mouse-arrow above, there is no error message given.
  • This is my source of my knowledge for the structure of my if: Support Microsoft - Is this the wrong type of documentation for me?

Got the solution now with your help (thanks to everyone who replied) - I wanted to extract a number with decimal from a string:

Function CleanString(strIn As String) As String
    Dim objRegex
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
     .Global = True
     .Pattern = "[^\d,] "
    CleanString = .Replace(strIn, vbNullString)
    End With
End Function

CodePudding user response:

The "If" line is written like an Excel formula. This is what is should look like in basic.

If IsNumeric(Val) Or Val = "," Then tmp = tmp & Mid(Text, i, 1)

The red text is a syntax error. If you go to the Debug menu and click Compile VBA Project, you'll get the error message.

The link that you included is for functions that are typed into a cell. You need a VBA reference. Here's a link to MS's reference, but a decent book would make your life a lot easier. Just search for "Excel VBA".

https://docs.microsoft.com/en-us/office/vba/api/overview/

CodePudding user response:

You can try something like this:

Function NurZahl (ByVal MyText As String) As Long

    ' Set up the variables
    Dim i as Integer
    Dim tmp as String
    Dim MyVal As String

    ' Start tmp with an empty string
    tmp = ""
    
    ' Loop through each character of the input MyText
    For i = 1 To Len(MyText)

      ' Read the character
      MyVal = Mid(MyText, i, 1)

      ' Check whether the character is a number or a comma
      ' and take reasonable action
      If IsNumeric(MyVal) or MyVal = "," then
          tmp = tmp & Mid(MyText, i, 1)
      End if

    Next i

    NurZahl = tmp

End Function

You'll have to change the code above to do what you want to do. The illustration above is to show how VBA code can be written.

In your VBA editor, when you see a red color on a line that means the editor has detected some issue with it.

If you were writing this function in Excel, you would typically use that function in a cell like this: =NurZahl(A1)

  • Related