Get Integer value from String using VBA - vba

I'm trying to automate a script using QTP and SAP.
In SAP an order is generated with Document number in status bar as "Standard PO created under the number 4500290636"
My challenge is how should I convert take string to an Integer value.

Since you are using SAP, I think it is safe to assume that the document number will always have a length of 10 characters. So, you can extract it using the Right function, then just convert it using Val. Something like this:
yourInteger = Val(Right(yourSAPString, 10))
Note: in .net, you could use Convert.ToInt32 instead of Val

You could use the split function:
Dim strSplit As Variant
Dim yourNumericOut As Variant
strSplit = Split("Standard PO created under the number 4500290636")
If IsNumeric(UBound(strSplit)) Then yourNumericOut = --strSplit(UBound(strSplit))
Then test for numeric, will allow for many lengths and could change the position of the number in the returned values.

I would recommend using a custom function.
Here is the function:
Public Function ExtractNumber(fromString As String) As Double
Dim RegEx As Object
Set RegEx = CreateObject("VBScript.RegExp")
With RegEx
.Pattern = "(\d{1,3},?)+(\.\d{2})?"
.Global = True
If .Test(fromString) Then
ExtractNumber = CDbl(.Execute(fromString)(0))
End If
End With
End Function
Here is the usage example:
Sub Example()
Debug.Print ExtractNumber("Standard PO created under the number 4500290636")
End Sub
This code was taken from a similar, more recent answer that has better solutions. See here:
Excel VBA - Extract numeric value in string

Related

defining code on vba excel to simplify code writing process

I am attempting to reduce the amount of clutter on my code by creating "shortcuts" if you will
For instance, I always have to type
ThisWorkBook.ActiveSheet.Range
Is there a way for me to define the above to create a less wordy macro? I have tried convert to range and string and the former returns an error (but I could still get intellisense recognize and attempt to autofill) while the string version doesnt work.
Just like in any programming language, you can use variables to store data
For example:
Dim myrange As Range: Set myrange = Sheets("Sheet1").Range("B5")
Alternatively, if you will be working with the same object multiple times, you can use the With keyword
For example. instead of writing you want to work with table every time on every new line you can do
With Sheets("Sheet1").ListObjects("Table1")
.ListRows.Add
.ListColumns(2).Range(3) = "Hello World!"
' ... and so on
End With
Also, please on a sidenote: Avoid using Select/ActiveSheet/ActiveWorkbook and so on!
More info on how to here
You can create functions or customized properties, which are always evaluated when called
Property Get pARng As Range
Set pARng = ThisWorkBook.ActiveSheet.Range
End Property
Function fARng As Range
Set fARng = ThisWorkBook.ActiveSheet.Range
End Function
'Usage
Sub xxx
'...
pARng.Rows(1).Activate
'Same as ThisWorkBook.ActiveSheet.Range.Rows(1).Activate
fARng.Rows(1).Activate
'using function instead achieves same result
End Sub

Extracting substring based on different criterias and placing the extracted string in another cell of same row

I have an excel file, in which there is a column containing a specific string. This string doesn't follow any particular pattern. My requirement is to extract a sub-string (product id) which is a set of 8 consecutive numbers that have to be preceded/followed by any no of characters or must be at the start or end of the string.
Following are some examples.
Scenario 1:
product id is preceded by #
Id#53298632/BS TVR:003519
Function used in excel
=MID(N88,FIND("#",N88)+1,8)
* result : 53298632 *
Scenario 2:
product id is at the beginning
53298632:003519
Function used in excel
=MID(A1,1,8)
* result : 53298632 *
At the beginning I had to deal with only scenario 1 and hence used the specified formula. Now a days the string doesnt follow any particular pattern but my product id still comes as 8 digit consecutive numbers. I searched for a suitable solution and found this formula (which I dont clearly understand).
=LOOKUP(10^8,MID(N132,ROW(INDIRECT("1:"&LEN(N132)-7)),8)+0)
This does work in most of the cases but in some cases it fails
For example
Pdr#53298632/ QTY NOS 1031949
Here the result is 1031949 which is definitely not what I want. The result should have been 53298632
Please help me fix this. Can this be done using VBA macro? I am completely new to such excel functions VBA and macro.
Any help will be highly appreciated!
Thanks in advance.
If you are happy to specifically include the Microsoft RegEx module into your Excel project, regular expressions will solve this reasonably quickly.
To add the RegEx function to use in your Excel Macros, select the Developer menu in Excel and start the Visual Basic editor. Within the VBA for Applications window, Select Tools->References and select Microsoft VBScript Regular Expressions 5.5.
Create a new Module for your VBAProject (right-click on your Excel file name in the project tree and click Insert->Module)
Double click on the newly created Module (within the project tree) and enter the following code in the Module1 (Code) window:
Public Function getProductCode(source As String) As String
Dim strPattern As String: strPattern = "(\d{8})"
Dim result As String: result = ""
Dim results As Object
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = False
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(source) Then
Set results = regEx.Execute(source)
If (results.Count <> 0) Then
result = results.Item(0)
End If
End If
getProductCode = result
End Function
From the relevant cell in Excel, you can now call the macro:
=getProductCode(A1)
I guess you could also modify the original formula to pick up the first match of an 8-digit number
=MID(A1,MATCH(TRUE,ISNUMBER(MID(A1,ROW(INDIRECT("1:"&LEN(A1)-7)),8)+0),0),8)
(must be entered as an array formula using CtrlShiftEnter).

MS Access VBA - Pulling a partial string from semi-consistent data in a field

I've looked around but wasn't able to find an exact solution...
I have an identifier-type field that generally follows the format of XXX-YY-ZZZZZZZZ. Sometimes the number of X's and Z's will vary, but the YY's are always enclosed between the two hyphens. If I wanted to create another field using just the "YY", what would be the best function to use? There's also another reference table with the YYs listed that I intend to relate it to.
Thanks in advance.
Sounds like you want to split the string into an array. Try this out
Public Sub Example()
Dim ExampleStr As String: ExampleStr = "XXX-YY-ZZZZZZZZ"
Dim StrArray() As String
StrArray = Split(ExampleStr, "-")
Debug.Print StrArray(1) ' Return the second element
End Sub

MS Access Remove Words from Text

I'm trying to remove various words from a text field in MS Access. The data might look like:
Hi there #foo, what's new #bar
#goodfriend and I just watched Star Wars
#this and #that and #theother
I want to remove all the words that start with '#'.
Replace() won't work since the words are different in each record.
Any ideas?
If you're using VBA, you should be able to replace text based on regular expressions. See the answer to replace a column using regex in ms access 2010 as an example.
I actualy upvoted CheeseInPosition's answer but just thought I would provide another way if you can't/don't want to do it with regex. Just wrote a quick function to parse out the words:
Public Function RemoveAtWords(strOriginal As String) As String
Dim strParts() As String
Dim i As Integer
strParts() = Split(strOriginal, " ")
For i = LBound(strParts) To UBound(strParts)
If Left(strParts(i), 1) <> "#" Then
RemoveAtWords = RemoveAtWords & " " & strParts(i)
End If
Next
RemoveAtWords = Trim(RemoveAtWords)
End Function
You can call that from a query and pass through your string. Not as efficient because you have to loop through the whole string, but just another option.

VBA - Convert string into Arithmetic Operator

Using VBA, I am trying to convert a string such as "/10" into an arithmetic operation, so that if I somehow connect it (depending on how it gets converted) after the number 200, the number 20 would be returned.
Thanks for any help.
What you're looking for is called a Math Parser. Look around for a library that you can use in VBA. If you're working in excel specific stuff - I'm sure excel already has a math parser built in - though I have no idea how you can gain access to it as the programmer. Maybe stick the expression in a cell as a string and call Eval().
EDIT
Microsoft intentionally removed this feature from function calls in excel, however it can be reinstated by creating the following function:
Function Eval(Ref As String)
Application.Volatile
Eval = Evaluate(Ref)
End Function
Then just call Eval("200" & "/10")
EDIT2
As noted in the comments below, modern versions of VBA support
Application.Evaluate("200" & "/10")
the below example provides a way of accomplishing what you are looking for.
Dim s As String
s = "/10"
Dim i As Integer
i = 200
Dim v
v = Evaluate(CStr(i) & s)
MsgBox v