For reasons obscure (I need to match some formatting used in an ancient Fortran code) I need to output from Excel using VBA (to a text file) some numbers in non-standard scientific notation.
For example if x = 6000000
normal VBA:
mystring = Format(x, "0.000E+00")
produces
"6.000E+06"
I need a way of producing
"0.600E+07"
instead. I can't figure out a way of doing this using Format functions. Is this possible?
This should do it:
Dim x As Double
x = 6000000
Dim myString As String
myString = "0" & VBA.Format(x, ".0000E+00")
Debug.Print myString
Related
In vb.net, I am attempting to format a string into a formatted Phone Number where the formatting is read in from a database variable.
A phone number like "5555555555" will get nicely formated into "(555) 555-5555" if the string is formatted in this fashion:
String.Format("{0:(###) ###-####}", Long.Parse(PhoneNum))
However, the "(###) ###-####" string is stored in a database, to maintain a central formatting choice for phone numbers in a theoretical system.
Does anyone know how I can substitute this hardcoded formatting for one with a variable? I am trying something like:
Dim phoneFormat as String = <~read in the String format from DB~>
String.Format("{0:" & phoneFormat.ToString & "}", Long.Parse(PhoneNum)))
Unfortunately however, this only returns the string itself. I am presented with "(###) ###-####".
Object.ToString is probably simpler, but you can still use String.Format. Here are these two methods
Dim phoneNum = "1234567890"
Dim phoneFormat = "(###) ###-####"
' simpler version using Long.ToString
Dim formattedPhoneNumber1 = Long.Parse(phoneNum).ToString(phoneFormat)
' your original attempt using String.Format
Dim formattedPhoneNumber2 = String.Format("{0:" & phoneFormat & "}", Long.Parse(phoneNum))
' cleaner version using String.Format with traditional interpolation and $ interpolation
Dim formattedPhoneNumber3 = String.Format($"{{0:{phoneFormat}}}", CLng(phoneNum))
Console.WriteLine(formattedPhoneNumber1)
Console.WriteLine(formattedPhoneNumber2)
Console.WriteLine(formattedPhoneNumber3)
Console.ReadLine()
(123) 456-7890
(123) 456-7890
(123) 456-7890
I think what you were probably not sending the Long into the function, rather the string (by the way why is the number 5555555555 being stored as a string in the first place?). You need to include Long.Parse() otherwise the #s in your format won't know what to operate on.
I have reduced my problem to the following code example. I am using a German Excel version in which separators in normal Excel formulas are semicolons ";" instead of "," (e.g. =SUMME(A1;A3) instead of =SUM(A1,A3)).
Now the code which works different from time to time:
Sub CommasDoNotWorkAnymore()
Dim a()
Dim i%
a = Array("A1,A3,A5", "B1", "B2")
i = 0
Debug.Print Sheets(1).Range(a(i)).Address
End Sub
Normally, when starting Excel, this code works. But sometimes Excel seem to switch the accepted separators used in the Range() to semicolons untill I restart Excel. This occurs most times when rerunning the code after a runtime error.
Is this a general Excel bug? Does anybody know what is behind this behaviour? Is there some Excel-wide "local option" for the Range class?
EDIT: I just tried to convert the a(i) with CStr(a(i) but this does also not work. So no ByRef kind of problem...
If you want to control it, check first what separator is currently in use. What I guess is that you want to know the list separator:
Application.International(xlListSeparator)
Check other separators here:
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-international-property-excel
The other time I had a problem with identifying decimal separator in VBA. Finnally I was able to get it in this way:
Function GetVBAdecimalSep()
Dim a(0) As Variant
a(0) = 1 / 2
GetVBAdecimalSep = Mid(a(0), 2, 1)
End Function
Changing separator not always works. Please see this: Changing decimal separator in VBA (not only in Excel)
The best solution is to check/change locale, even temporary.
Application.LanguageSettings.LanguageID(msoLanguageIDUI)
gives the LCID which would be 1033 for English (US)
Initially it is important to note that I use MS Excel in Brazilian Portuguese.
That's my code:
Dim C1 As Integer
Dim C2 As Integer
Dim Cod As String
C1 = Worksheets("Dictionary").Range("D1").Value
C2 = Worksheets("Dictionary").Range("D2").Value
Cod = C1 & "." & C2
Worksheets("Dictionary").Range("D3").Value = Cod
Cells:
D1 = 1
D2 = 2
I expected that the output would be "1.2", but it's "1,2"!
What am I doing wrong?
And I apologize for my rusty English
Thank you!
Try this before outputting the value to the range:
Worksheets("Dictionary").Range("D3").NumberFormat = "#"
This changes the format of the cell to Text which prevents Excel to interpret the value you write to it as a number.
You use your Excel in "Brazilian Portuguese". The change may be due to the International Settings in the Windows Control Panel.
If your International Settings define the "," as the decimal separator, then Excel will convert the dot to the comma when you make the assignment in Visual Basic. This behavior makes the VBA code independent of locale settings and so makes the code portable in the international context (I assume that is the intention of this behavior).
If Brazilian Portuguese needs the dot as separator, then set your computer to use the dot as decimal separator, however, it shouldn't matter because when you send the spreadsheet to Brazil, the Excel there will use the correct decimal separator (I assume numbers are stored as binary floating point so dot or comma is only a matter of presentation).
EDIT: strikethrough of text above that would seem a workaround, as setting the international seting/decimal separator makes no difference for the end result.
Sub Replace()
Sheet1.Range("B1").Value = "=SUBSTITUTE(A1,""."","","")"
End Sub
You can change your range accordingly.
Example - Range("B1:B3").Value = "=SUBSTITUTE(A1:A3,""."","","")"
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
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