VBA change string with decimal to number with decimal - vba

I have a field in an access database as TEXT. the text has decimals such as 100.00000. need to run calcs on these with the decimals present. Ive been working with the SQL statement and CAST functions and ive had no luck. All I get is whole numbers with no decimals. I've resorted to VBA and I am still getting the same results. every result is whole numbers. I would prefer 5 (FIVE) decimal places.
such as 100.00000 and not "100".
I've tried the split function in VBA and re assembling the 2 strings into a number with the decimal present and still no luck.
The code below pulls in whole numbers only - I need decimal places!! thank you
Function numChange(input1 As String) As Integer
Dim output As Integer
If input1 = "" Then
input1 = 0
End If
output = Format(input1, Number)
numChange = output
End Function

after decimal if no zero will mean a thing, but if you have 100.00001 this will return the same.
Modified:
Function numChange(input1 As String) As Double
Dim output As Double
If input1 = "" Then
input1 = 0
End If
output = Format(input1, "0.00000")
numChange = output
End Function

Related

Convert string to double in word (vba)

I am trying to convert a text in a word document to be a double, so I can do currency formatting on it. I receive this text from a mail merge. How would I create a macro that can receive this text and return it as a number?
I'm unfamiliar with word, and VBA script. What I have made so far is
Function stringToDouble(baseString As String)
Dim num As Double
num = Val(baseString)
stringToDouble = num
End Function
I'm not sure how I would call this macro. Because it takes a parameter it does not show up in the macro table.
I may be completely off on how to convert text to a double in word, but any help is appreciated.
Thanks. Please comment for any clarifications.
You don't need a macro for this!!! All you need do is learn how to use formatting switches in Word fields.
To control number & currency formatting in Word, add a numeric picture switch to the mergefield. To do this:
select the mergefield;
press Shift-F9 to reveal the field coding. It should look something like {MERGEFIELD MyData};
edit the field so that you get {MERGEFIELD MyData # $,0.00} (or whatever other numeric format you prefer - see below);
position the cursor anywhere in this field and press F9 to update it.
Note 1: The '# $,0.00' in the field is referred to as a numeric picture switch. Other possibilities include:
# 0 for rounded whole numbers
# ,0 for rounded whole numbers with a thousands separator
# ,0.00 for numbers accurate to two decimal places, with a thousands separator
# $,0 for rounded whole dollars with a thousands separator
# "$,0.00;($,0.00);'-'" for currency, with brackets around negative numbers and a hyphen for 0 values
Note 2: The precision of the displayed value is controlled by the '0.00'. You can use anything from '0' to '0.000000000000000'.
If you use a final ';' in the formatting switch with nothing following, (eg # "$,0.00;($,0.00);") zero values will be suppressed. Note that this suppresses 0s resulting from empty fields and from fields containing 0s.
Note 3: If you use a decimal tab or right-aligned tab to align the values, wrap the switch in quotes (i.e. # "$,0.00") and insert a tab into the field code after the $ sign, you can have the values output with the decimal alignment occurring after the $ sign.
For more Mailmerge Tips & Tricks, see: https://www.msofficeforums.com/mail-merge/21803-mailmerge-tips-tricks.html
If you want to convert the number to a Double data type then try this:
Function StringToDouble(ByVal baseString As String) As Double
StringToDouble = VBA.CDbl(baseString)
End Function
If you're only concerned about formatting currency, convert the string to the Currency data type like this:
Function StringToCurrency(ByVal baseString As String) As Currency
StringToCurrency = VBA.CCur(baseString)
End Function
You will still need to format the number but both functions give you a number that can be formatted.
Here's an example that also gives you a string formatted as USD (e.g. $4,999.75). It requires the StringToCurrency function above.
Sub test()
Dim stringNum As String
stringNum = "4,999.754501"
Debug.Print "stringNum=" & stringNum ' outputs 4,999.754501
Dim currencyNum As Currency
currencyNum = StringToCurrency(stringNum) ' outputs 4999.7545
Debug.Print "currencyNum=" & currencyNum
Dim formattedString As String
formattedString = Format$(currencyNum, "$#,##0.00")
Debug.Print "formattedString=" & formattedString ' outputs $4,999.75
End Sub

Change format (need to have a comma in my data) Excel 2013 VBA

I calculate data directly in a userform and I transfer my data into a table afterwards. In my userform the numbers are good, but not in the table. I would like that my data (Double) appear with a comma in my table. For now, my data are in the table without comma. For example, my data is 441 666 666 666 667 instead of 4,41666666666667 ... I think that I have to change the format? Can anyone enlighten me on this subject please? Thank you.
Code example:
Private Sub tbxHours_Change()
Dim rate As String
Dim hours As String
rate = Replace(tbxRate .Value, ".", ",")
hours = Replace(tbxHours .Value, ".", ",")
If StrComp(rate , "") = 0 Then rate = "0"
If StrComp(hours , "") = 0 Then hours = "0"
tbxCostRate.Value = CStr(CDbl(rate) * CDbl(hours))
End sub
I'm not following your code completely, but this is the format you want to apply to your values.
.NumberFormat = "#,##0"
You are using the comma as the decimal delimiter, correct? If so, make sure that the settings are correct in excel. See Microsoft Change Character for Delimiter
This can be done this with the VBA Format() function:
'Comma as the Decimal Delimiter
tbxCostRate.Value = Format(CDbl(rate) * CDbl(hours), "#.##0,00")
'Comma as the Thousands delimiter
tbxCostRate.Value = Format(CDbl(rate) * CDbl(hours), "#,##0.00")
*Note: the rate probably shouldn't be converted to a string if the data is numeric
Also:
tbxCostRate.Value = Format CStr(CDbl(rate) * CDbl(hours)), "Standard")

Visual Basic programming

I am new to the programing world and I am stuck on the below problem please could you assist me
Write a Visual Basic.net function to calculate the sum of all the numbers in an input field. For example, if the input string is: "ICT2611", then the numbers included in this string are: 2, 6, 1, 1 and their sum is therefore, 2+6+1+1 = 10
The below should solve your problem, it uses Regex to find any matches in the provided string to the expression (numbers 1 - 9), and then iterates through them tallying them up as it goes.
Public Function SumOfString(str As String) As Integer
Dim total As Integer = 0
For Each i As Match In Regex.Matches(str, "[1-9]")
total += i.Value
Next
Return total
End Function
Alternatively the same thing could be achieved like this, this just iterates through each character in the string and then checks to see if it's a digit. If it is a digit then it'll tally it up.
Public Function SumOfString(str As String) As Integer
Dim total As Integer = 0
For Each i As Char In str
If Char.IsDigit(i) Then total += Integer.Parse(i)
Next
Return total
End Function

How do I convert integer to 4-digit hex string?

I need to convert a 2-byte signed integer into a string of it's hex equivalent, but I need the string to be 4 characters. I've tried the Hex() function but when I convert 0 or say, 10, the result is 0 or A. I need the result to be 0000 or 000A. Any tips or advice?
It is just
Dim hexS As String = i.ToString("X4")
This is well explained in the The Hexadecimal (X) Format specifier.
The 4 after the X specifies how many chars you want in the output and if there are not enough chars, the missing ones are supplied as an appropriate number of "0".
Since you also tagged the question VBA, here is a VBA way to do it
Right("0000" & Hex(i), 4)
Use
Dim i As Integer = 10
Dim hexS As String = i.ToString("X4")
If you are deadset on using Hex as opposed to string formatting then you could use:
Dim Number As Integer
Dim Output As String
Number = 10
Output = ("000" & Hex(Number))
Output = Output.Substring(Output.Length - 4, 4)
Console.WriteLine(Output)
Alternatively make use of string formatting for numbers as so:
Output = Number.ToString("X4")
Console.WriteLine(Output)
The output in both cases with be 000A.
The VB way
Format(i, "X4")
or
Hex(i).PadLeft(4, "0"c)
In Visual Studio 2015:
s = $"{i:X4}"

Extract 5-digit number from one column to another

I need help with extracting 5-digit numbers only from one column to another in Excel 2010. These numbers can be in any position of the string (beginning of the string, anywhere in the middle, or at the end). They can be within brackets or quotes like:
(15478) or "15478" or '15478' or [15478]
I need to ignore any numbers that are less than 5 digits and include numbers that start with 1 or more leading zeros (like 00052, 00278, etc.) and ensure that leading zeros are copied over to the next column. Could someone help me with either creating a formula or UDF?
Here is a formula-based alternative that will extract the first 5 digit number found in cell A1. I tend to prefer reasonably simple formula solutions over VBA in most situations as formulas are more portable. This formula is an array formula and thus must be entered with Ctrl+Shift+Enter. The idea is to split the string up into every possible 5 character chunk and test each one and return the first match.
=MID(A1,MIN(IF(NOT(ISERROR(("1"&MID(A1,ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE)),5)&".1")*1))*ISERROR(MID(A1,ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE))+5,1)*1)*ISERROR(MID(A1,ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE))-1,1)*1),ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE)),9999999999)),5)
Let's break this down. First we have an expression I used twice to return an array of numbers from 1 up to 4 less than the length of your initial text. So if you have a string of length 10 the following will return {1,2,3,4,5,6}. Hereafter the below formula will be referred to as rowlist. I used R1C1 notation to avoid potential circular references.
ROW(INDIRECT("R1C[1]:R"&(LEN(A1)-4)&"C[1]",FALSE))
Next we will use that array to split the text into an array of 5 letter chunks and test each chunk. The test being performed is to prepend a "1" and append ".1" then verify the chunk is numeric. The prepend and append eliminate the possibility of white space or decimals. We can then check the character before and the character after to make sure they are not numbers. Hereafter the below formula will be referred to as isnumarray.
NOT(ISERROR(("1"&MID(A1,rowlist,5)&".1")*1))
*ISERROR(MID(A1,rowlist+5,1)*1)
*ISERROR(MID(A1,rowlist-1,1)*1)
Next we need to find the first valid 5 digit number in the string by returning the current index from a duplicate of the rowlist formula and returning a large number for non-matches. Then we can use the MIN function to grab that first match. Hereafter the below will be referred to as minindex.
MIN(IF(isnumarray,rowlist,9999999999))
Finally we need to grab the numeric string that started at the index returned by the MIN function.
MID(A1,minindex,5)
The following UDF will return the first five digit number in the string, including any leading zero's. If you need to detect if there is more than one five digit number, the modifications are trivial. It will return a #VALUE! error if there are no five-digit numbers.
Option Explicit
Function FiveDigit(S As String, Optional index As Long = 0) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = "(?:\b|\D)(\d{5})(?:\b|\D)"
.Global = True
FiveDigit = .Execute(S)(index).submatches(0)
End With
End Function
As you may see from the discussion between Mark and myself, some of your specifications are unclear. But if you would want to exclude decimal numbers, when the decimal portion has five digits, then the regex pattern in my code above should be changed:
.Pattern = "(?:\d+\.\d+)|(?:\b|\D)(\d{5})(?:\b|\D)"
I just wrote this UDF for you , basic but will do it...
It will find the first 5 consecutive numbers in a string, very crude error checking so it just says Error if anything isn't right
Public Function GET5DIGITS(value As String) As String
Dim sResult As String
Dim iLen As Integer
sResult = ""
iLen = 0
For i = 1 To Len(value)
If IsNumeric(Mid(value, i, 1)) Then
sResult = sResult & Mid(value, i, 1)
iLen = iLen + 1
Else
sResult = ""
iLen = 0
End If
If iLen = 5 Then Exit For
Next
If iLen = 5 Then
GET5DIGITS = Format(sResult, "00000")
Else
GET5DIGITS = "Error"
End If
End Function