Reference part of a cell in excel vba - excel

I wanted to know a way to reference part of a value in a cell in Excel in VBA. For instance if in cell A32 I have stored 4200 cc. I would like to reference only the 4200 for calculations in a macro in VBA. So like one can reference strings or lists in python with indices, I'd like to be able to do the same. Thank you!

Something like this(?):
Dim tmpArr
tmpArr = Split(Range("A32"), " ")
'any calculation in vba in this way:
Range("B32") = tmpArr(0) / 100
'results with 42 in cell B32
EDIT If there is any doubt about recognition of number for first part of the split results you could make additional conversion in this way:
'conversion to Double type
Range("B32") = CDbl(tmpArr(0))/100

You may create a function to split the content of the cell and then handle the parts you want separately.
Dim content As Variant
content = Split(Range("A32").Value, " ")

Get the cell value as a string s and return the numeric part?
Function GetNumber(s As String)
Dim j As Long
While Not IsNumeric(Left(s, 1))
If Len(s) <= 1 Then
Exit Function
Else
s = Mid(s, 2)
End If
Wend
GetNumber = Val(s)
End Function

Related

Extracting digits from strings in excel with condition

Say we have strings like this and want to output digits out from it. The digits is not always in the beginning so I think I need to define condition as well.
Tried this Excel: Extract Numbers from Date Strings
but not working
how can we extract the digits from this kind of string in excel?
Congrats, today is the day you are going to add some vba knowledge to your arsenal. This is how the result would look, if you add a vba formula to it:
In order to add the formula, press Alt+F11 and paste the following code either in Modul1 or in the Worksheet:
Public Function ExtractString(myRange As Range) As String
Dim i As Long
Dim result As String
Dim currentString As String
Dim okIndex As Long
okIndex = 1
result = ""
For i = 1 To Len(myRange.Text)
currentString = Mid(myRange.Text, i, 1)
If IsNumeric(currentString) And okIndex >= 1 Then
result = result & currentString
okIndex = okIndex + 1
Else
If okIndex > 1 Then okIndex = -1
End If
Next
ExtractString = result
End Function
If you prefer a formula solution, you can use:
=AGGREGATE(14,6,--MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789")),ROW(INDEX($A:$A,1):INDEX($A:$A,LEN(A1)))),1)
If you have O365 with the most recent updates, you can use:
=AGGREGATE(14,6,--MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789")),SEQUENCE(LEN(A1))),1)
If you need to check for no-digits in the string, you can wrap the formula in IFERROR. eg:
=IFERROR(AGGREGATE(14,6,--MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&"0123456789")),SEQUENCE(LEN(A1))),1),"")

How can i extract the numeric part of a cell content in Excel?

I am working on different set of data an would like to extract only numeric part of them from an excel sheet.
How could I do to extract only the numeric part please?
For example:
"A51sd5dd5$1" I just need 51551
"Bd203m01,02" I just need 2030102
I need of an Excel formula, or Vba function if you may help please.
Thank you in advance for your help
Welcome in the Forum! I think this is the kind of function you need to have.
I tested your examples and they are giving the right value in numeric of course.
Here is the function:
Function GetNumeric(CellRef As String)
Dim StringLength As Integer
StringLength = Len(CellRef) 'This is the Length of the CellRef entry
Dim n As Long
Dim sResult As String 'Store in a result variable the numeric characters
For n = 1 To StringLength
'iterate through each character and test if it is numeric
If IsNumeric(Mid(CellRef, n, 1)) Then sResult = sResult & Mid(CellRef, n, 1)
Next n
'Return your value
GetNumeric = sResult
End Function
I hope it will help you!
If you have Office 365 and TEXTJOIN function available to you then you can use below formula assuming your data is in cell A1.
=TEXTJOIN("",TRUE,IFERROR(MID(A1,ROW($A$1:INDEX(A:A,LEN(A1))),1)+0,""))
EDIT:
Following is a formula which you can use for Excel Versions later than 2007. If you have older than 2007 then IFERROR part needs to be re-worked.
=NPV(-0.9,IFERROR(MID(A1,(LEN(A1)+1)-ROW($A$1:INDEX(A:A,LEN(A1))),1)*0.1,""))

Is possible find the value not equal to one in the column and get all position in the same field?

I need to find the value not equal 1 in the column A and get all the position in the same field.
I want to get the all not equal 1 position into the B11.
I want to use the excel formula function and don't use vba or other code. How can I do ? Is possible ?
Since you are working with Excel-2007, unfortunately you won't be able to use the new TEXTJOIN() and CONCAT() functions (nor power query). However you can get quite creative with a function like CONCATENATE(), it will most likely mean at some point you'll have to do some manual 'labour'. Who wants to do manual labour? ;)
So in this case I would prefer to go the UDF way. Below a tested example:
Function GetPos(RNG As Range, VAL As Double) As String
Dim CL As Range, ARR() As String, X as double
X = 1
For Each CL In RNG
If CL.Value <> VAL Then
ReDim Preserve ARR(X)
ARR(X) = CL.Address(False, False)
X = X + 1
End If
Next CL
If IsEmpty(ARR) Then
GetPos = "No hits"
Else
GetPos = Join(ARR, ",")
GetPos = Right(GetPos, Len(GetPos) - 1)
End If
End Function
This one takes two criteria, a range and a numeric value indicating what the cells in your range must NOT be. It will return a string value.
Call it from your worksheet through =GETPOS(A1:A10,1) and it should return A2,A7,A9
EDIT
If you are fine using a helper column you could do it like so:
Formula in B1:
=IF(A1<>1,"A"&ROW()&",","")
Formula in B11:
=LEFT(B1&B2&B3&B4&B5&B6&B7&B8&B9&B10,SUM(LEN(B1:B10))-1)
Enter through CtrlShiftEnter
Note: If you don't want to use a helper column you'll have to use TRANSPOSE() to 'load' an array of text values but it involves manual labour and IMO you'll surpass your goal.

Highlight cells in selection that contain formulas with constants

I am working on a budget in excel 2007. It was written by someone else and contains many sheets and many formulas. I am trying to make the spreadsheet more efficient by creating an Input worksheet where all/most constants would be entered. To help with this process, I would like to be able to highlight all formulas that contain constants as well as highlight all constants (not in formulas) within my selection. Or, if easier, the opposite, highlight all formulas that do not contain constants within my selection. I am mainly dealing with numbers, not text.
Here are examples of formulas(=) with constants and just constants:
=82000-50000
=$A$2-50000
=A2-50000
=F133***.05**
50000
Here are examples of formulas(=) that do not contain constants:
=SUM(E8:P8)
=$C$51*'Servicing Detail'!$E$181
=K152
The closest answer I could find to my question was here: How to determine if a cell formula contains Constants?. But I believe this post to be specific to finding quotations within a formula as Siddharth Rout clarified in his last comment.
Any help would be greatly appreciated. Thank you. (This is my first post and hope that I have formatted correctly. Apologies in advance)
You can parse formulas using the SPLIT function in VBA. E.g. the code below works for the examples you have given. Returns TRUE if formula contains constants, returns N/A if it is not a formula and FALSE otherwise.
Probably you have to adapt a little bit so it works in all cases, but it's a good starting point.
Function HasConstant(r As Range) As Variant
Application.Volatile
Dim formula As String
Dim delimiters() As String
Dim delimiter As Variant
Dim Components() As String
Dim component As Variant
Dim chars As Integer
delimiters() = Split("+ - * / = & ( ) ,")
If r.HasFormula Then
formula = Right(r.formula, Len(r.formula) - 1)
Do Until formula = ""
chars = Len(formula)
component = formula
For Each delimiter In delimiters
Components = Split(formula, delimiter)
If Len(Components(0)) < chars And Len(Components(0)) > 0 Then
component = Components(0)
chars = Len(component)
End If
Next
If IsNumeric(Replace(component, ".", Application.International(xlDecimalSeparator))) Then 'IsNumeric(component)
HasConstant = True
Exit Function
ElseIf Left(CStr(component), 1) = Chr(34) And Right(CStr(component), 1) = Chr(34) Then
HasConstant = True
Exit Function
End If
If chars < Len(formula) Then
formula = Right(formula, Len(formula) - chars - 1)
Else
formula = ""
End If
Loop
Else
HasConstant = CVErr(xlErrNA)
Exit Function
End If
HasConstant = False
End Function
Example:

Function to merge excel data referencing a count using VBA

I'm trying to write a function that merges multiple rows of text in a column into a single cell based on a pre determined count. My goal is to generate a flexible function to aid in compiling / interperting large quantaties of data. The code I've written returns #NAME? and I cant figure out where the error is. My code is as follows:
Function vmrg(countref As Integer, datref As Integer) As String
If IsEmpty(ActiveCell.Offset(0, -countref)) Then % check if cell containing count is blank
vertmerge = "N/A" % if blank, state N/A
Else
Dim datlst(0 To ActiveCell.Offset(0, -countref).Value - 1) As String
Dim i As Integer
For i = 0 To ActiveCell.Offset(0, -countref).Value - 1
datlst(i) = ActiveCell.Offset(i, -datref).Text %fill array with data
End
vertmerge = datlst(0)
For i = 1 To ActiveCell.Offset(0, -countref).Value - 1 % merge array to a single string
vertmerge = vertmerge & ", " & datlst(i)
End
End
End Function
I have matlab and some C++ experience but this is the first time I've used VBA so my syntax is probably odd in some areas and wrong in others. Ideally I would like to reference the cells where the data and count info are stored, but for now I'm hoping to correct my syntax and set a jumping off point for further development of this function. Any reccomendations are appreciated.
Code Rev_1: I still have an output of #NAME? but I think I've corrected(?) some of the issues
Function vertmerge(countref As Range, datref As Integer) As String
If IsEmpty(countref) = True Then
vertmerge = "NA"
Else
Dim datlst(0 To countref.Value - 1) As String
Dim i As Integer
For i = 0 To countref.Value - 1
datlst(i) = countref.Offset(i, datref).Text
Next i
vertmerge = datlst(0)
For i = 1 To countref.Value - 1
vertmerge = vertmerge & ", " & datlst(i)
Next i
End
End Function
You are doing some dangerous things here!
First - you are referencing "ActiveCell" from inside a function; but you have NO IDEA what cell will be active when the function runs! Instead, pass the target cell as a parameter:
=vmrg("B6", 5, 6)
and change your function prototype to
Function vmrg(r as Range, countref as Integer, datref as Integer)
Now you can reference things relative to r with
r.Offset(1,2)
etc.
Next - you are never assigning anything to vmrg. In VBA, the way a function returns a value is with (in this case)
vmrg = 23
You are assigning things to a variable called vertmerge - but that is not the name of your function. At least add
vmrg = vertmerge
Just before returning. That might do it. Without a full sample of your spreadsheet I can't help you more.

Resources