Excel - Using IF and OR - excel

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

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://learn.microsoft.com/en-us/office/vba/api/overview/

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

Transforming a sub to a function in v.b.a that converts html from a cell to rich text

I have copied a code which runs a string in html format into the I.E. web browser, which converts it to rich text, then copies it back into the cell that the code was run on. I've included the code below.
However, I want the ability to run this sub as a function for other users so they will never have to access the developer tab. I'm stuck on how to convert this sub into a function so it would be great if someone could help me out.
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
.ExecWB 17, 0: .ExecWB 12, 2
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
.Quit
End With
End Sub
Thanks for all the responses.
for example, in cell A1 I have '< html > this is < b > a custom text < / b>'. I want to be able to write in cell A2 '=sample(A1)', and for the text in A1 to be converted into formatted text, ie. 'this is a custom text' by the code I've included. The cell A2 would have the converted text in.
This UDF addresses the use case given in the question. The function uses a regular expression to parse out the text to be bolded and then leverages Mark.R's code from a few years ago to translate the character values to the equivalent unicode bold character values. This code only handles the <b> tag but it could easily be extended to handle the <i> tag.
Option Explicit
Function EmboldenText(ByVal source As Range) As String
Dim re As VBScript_RegExp_55.RegExp
Dim m As VBScript_RegExp_55.Match
Dim strIn As String
Dim strout As String
Dim start As Integer
Set re = New VBScript_RegExp_55.RegExp
re.Pattern = "<b>(.+?)</b>"
re.Global = True
strIn = source.Value
strout = ""
start = 1
For Each m In re.Execute(strIn)
strout = strout & Mid(strIn, start, m.FirstIndex - start + 1) & _
Bold(m.SubMatches(0))
start = m.FirstIndex + m.Length + 1
Next m
EmboldenText = strout & Mid(strIn, start)
End Function
You will need to add this library to your references if you want to try this solution.

How to remove the last character of a word in a text string and insert to another cell using VBA in Excel?

Everything is working except for that little comma in the 5th word. How to remove that? My code is as follows.
The text looks like this: The data as of 20.12.2019, and so on.
I only want 20.12.2019 without that comma. Any clue? Thanks.
Public Function FindWord(Source As String, Position As Integer)
Dim arr() As String
arr = VBA.Split(Source, " ")
xCount = UBound(arr)
If xCount < 1 Or (Position - 1) > xCount Or Position < 0 Then
FindWord = ""
Else
FindWord = arr(Position - 1)
End If
End Function
subroutine calls the function.
Sub InsertDate()
Sheets("Sheet1").Range("B3").Value = FindWord(Sheets("Sheet2").Range("A2"), 5)
End Sub
So just for fun, a short introduction to regular expressions (which, by no means, I am an expert in):
Sub Test()
Dim str As String: str = "The data as of 20.12.2019, and so on."
Dim regex As Object: Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "\b(\d{2}.\d{2}.\d{4})"
regex.Global = True
Debug.Print regex.Execute(str)(0)
End Sub
This would be good practice if your string won't follow that same pattern all the time. However when it does, there are some other good alternatives mentioned in comments and answers.
One option is to Replace:
Sub InsertDate()
With Sheets("Sheet1").Range("B3")
.Value = FindWord(Sheets("Sheet2").Range("A2"), 5)
.Value = Replace(.Value, ",", "")
End With
End Sub
This is still text-that-looks-like-a-date, so you can call DateValue to convert it.
.Value = Replace(.Value, ",", "")
.Value = DateValue(.Value) '<~ add this line

Extract numbers from cells of varying lengths/formats

I am looking for a formula to extract digits from column A. The problem I am running into is the varying lengths and formats. I am seeking a solution based on the desired result column below.
Formula in Column B:
=IFERROR(INT(LEFT(REPLACE(SUBSTITUTE(A4,"-"," "),1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A4&1/17))-1,""),5)),INT(LEFT(REPLACE(SUBSTITUTE(A4,"-"," "),1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A4&1/17))-1,""),4)))
Workbook:
Thank you!
Try the following User Defined Function:
Public Function LastNumber(s As String) As Variant
Dim L As Long, i As Long, temp As String, arr
Dim CH As String
L = Len(s)
temp = ""
For i = 1 To L
CH = Mid(s, i, 1)
If CH Like "[0-9]" Then
temp = temp & CH
Else
temp = temp & " "
End If
Next i
arr = Split(Application.WorksheetFunction.Trim(temp), " ")
For i = UBound(arr) To LBound(arr) Step -1
If IsNumeric(arr(i)) Then
LastNumber = CLng(arr(i))
Exit Function
End If
Next i
LastNumber = ""
End Function
It will return the last number (set of numerals) in a string.
User Defined Functions (UDFs) are very easy to install and use:
ALT-F11 brings up the VBE window
ALT-I
ALT-M opens a fresh module
paste the stuff in and close the VBE window
If you save the workbook, the UDF will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the UDF:
bring up the VBE window as above
clear the code out
close the VBE window
To use the UDF from Excel:
=myfunction(A1)
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
and for specifics on UDFs, see:
http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx
Macros must be enabled for this to work!
Try this user defined function in a standard public module code sheet.
function lastNumber(str as string)
dim i as long, tmp as string
tmp = str
for i=len(tmp) to 1 step-1
if asc(right(tmp, 1))<48 or asc(right(tmp, 1))>57 then
tmp = left(tmp, len(tmp)-1)
else
exit for
end if
next i
for i=len(tmp) to 1 step-1
if asc(mid(tmp, i))<48 or asc(mid(tmp, i))>57 then
exit for
end if
next i
lastNumber = mid(tmp, i+1)
end function
You could use Regex, which needs a reference to Microsoft VBScript Regular Expressions:
Public Function GetLastNum(str As String) As String
Dim numRegEx As RegExp
Set numRegEx = New RegExp
Dim matchColl As MatchCollection
Dim retStr As String
With numRegEx
.Global = True
.Pattern = "[0-9]+"
Set matchColl = .Execute(str)
If matchColl.Count > 0 Then
GetLastNum = matchColl.Item(matchColl.Count - 1)
Exit Function
End If
End With
End Function

Excel VBA - how to find the largest substring value in a column

I have a column in a spreadsheet.
The format of the data in each cell is aa-0001-xx.
I need to examine the whole column to find the highest value of the sequence number. this would be the substring from column4 thru column7.
I can find the sequence number using Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4)
But I need to find the max sequence in the whole column.
I am doing this in VBA.
Any help would be appreciated.
Here is my code so far:
Private Sub CommandButton1_Click()
Dim sQuoteNumber As String
Dim sFileName As String
Dim sPathName As String
Dim checkit As String
'Log the Quote
'First, open the log file and determine the next sequential log number.
sPathName = "C:\Users\Rich\Documents\Bryan\BigProject\"
sFileName = "QuoteLog2016.xlsx"
ControlFile = ActiveWorkbook.Name
Workbooks.Open Filename:=sPathName & sFileName
'Create the new Quote Number
checkit = Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4) ' This is a temp test line
If Mid(ActiveWorkbook.Sheets("Sheet1").Range("B2:B2"), 4, 4) = "" Then
sQuoteNumber = "16-0001"
Else
'find the biggest number
'Here I was looking to like pass the mid function to a Max function of some sort.
sQuoteNumber = "16-0002"
End If
MsgBox ("The new Quote Number is: " + sQuoteNumber)
'Save the log entry
Workbooks(sFileName).Close
All of the comments made to your answer would work well for you. It's also true that there's no evidence in your code at having attempted something, however rudimentary, and this is why answers to a rather trivial task are not forthcoming for you. Perhaps, in future, have a go at some kind of solution ( even if it feels more guesswork than anything) and people on this site will be much more supportive of you.
To set you on your way, you could make use of the Split() function which converts a String into a String array, separated by a nominated value - in the case of your quotations, you could use "-" as your separator. This might be easier than your Mid function and will deal with the case of different sized quotations.
The code below will get you started but you'd want some error handling in there to test, for example, that each cell splits appropriately or that any cells aren't blank. I'll leave all of that to you.
Option Explicit
Private mLastQuote As Long
Public Sub Test()
Initialise 'call this routine just once at the start of your project
MsgBox GetNextQuote(16) 'use the GetNextQuote() function to get next number
MsgBox GetNextQuote(16)
MsgBox GetNextQuote(16)
End Sub
Private Function GetNextQuote(prefix As Integer) As String
mLastQuote = mLastQuote + 1
GetNextQuote = CStr(prefix) & "-" & _
Format(mLastQuote, "000#")
End Function
Private Sub Initialise()
Const PATH_NAME As String = "C:\Users\Rich\Documents\Bryan\BigProject\"
Const FILE_NAME As String = "QuoteLog2016.xlsx"
Const QUOTE_COL As String = "B"
Dim wb As Workbook
Dim ws As Worksheet
Dim v As Variant
Dim r As Long
Dim parts() As String
Dim num As Long
Application.ScreenUpdating = False
Set wb = Workbooks.Open(PATH_NAME & FILE_NAME, True, True)
Set ws = wb.Worksheets("Sheet1")
'Read quote values into variant array
With ws
v = .Range(.Cells(2, QUOTE_COL), _
.Cells(.Rows.Count, QUOTE_COL).End(xlUp)) _
.Value2
End With
'Find max quote
For r = 1 To UBound(v, 1)
parts = Split(v(r, 1), "-") 'splits quote into 3 parts
num = CLng(parts(1)) 'index (1) is the middle part
If num > mLastQuote Then mLastQuote = num
Next
wb.Close False
Application.ScreenUpdating = True
End Sub

Removing particular string from a cell

I have text in a range of cells like
Manufacturer#||#Coaster#|#|Width (side to side)#||#20" W####Height (bottom to top)#||#35" H#|#|Depth (front to back)#||#20.5" D####Seat Depth#||#14.25"**#|#|Material & Finish####**Composition#||#Wood Veneers & Solids#|#|Composition#||#Metal#|#|Style Elements####Style#||#Contemporary#|#|Style#||#Casual
From this cell i need to remove strings between #|#|"needtoremove"#### only without affecting other strings.
I have tried find and replace, finding #|#|*#### and replacing it with #|#|. However its not giving the exact result.
Can anyone help me?
The other solution will remove anything between the first #|#| and ####, event the #||# etc.
In case you only need to remove the text between #|#| and #### only if there is no other ##|| inbetween, I think the simplest way is to use a regex.
You will need to activate the Microsoft VBScript Regular Expressions 5.5 library in Tools->References from the VBA editor.
Change range("D166") to wherever your cell is. The expression as it is right now ("#\|#\|[A-Za-z0-9& ]*####")matches any text that starts with #|#|, ends with #### and has any number of alphanumerical character, & or space. You can add other caracters between the brakets if needed.
Sub remove()
Dim reg As New RegExp
Dim pattern As String
Dim replace As String
Dim strInput As String
strInput = Range("D166").Value
replace = ""
pattern = "#\|#\|[A-Za-z0-9& ]*####"
With reg
.Global = True
.MultiLine = True
.IgnoreCase = False
.pattern = pattern
End With
If reg.test(strInput) Then Range("D166").Value = reg.replace(strInput, replace)
End Sub
Something like this.
If that value is in cell A1
Dim str As String
Dim i As Integer
Dim i2 As Integer
Dim ws As Excel.Worksheet
Set ws = Application.ActiveSheet
str = ws.Range("A1").Value
i = InStr(str, "#|#|")
i2 = InStr(str, "####")
str = Left(str, i) & Right(str, Len(str) - i2)
ws.Range("A1").Value = str

Resources