apply user-defined format in excel 2007 vba - vba

The excel 2007 format i am using is: #,##0.00,,,_);[Red](#,##0.00,,,);"-"
if is is possitive, i want the number to display in billions; if negative, in billions and in parentahis; if missing, "-".
It works fine with excel 2007. But when i tried to apply the format in vba, it did not work.
Please use the following numbers as example:
-11467478
224785.66
-5579046
1904770.9
-14916968
The data type i used is variant. shall i use long?
my initial code is something like:
......
with worksheet
'cells(1,1) would be any of the above numbers
.Cells(1, 1).NumberFormat = "#,##0.00,,,_);[Red](#,##0.00,,,);" - ""
end with
.....
I got an erros message run-time error 13, type mismatch
I even tried to decompose the format. but it still did not work.
i am quite new to vba. could anyone help me?
......

This will also work, the dash is one of the characters that don't need to be escaped...
"#,##0.00,,,_);[Red](#,##0.00,,,);-"

You need to use double " for the minus sign. I tested your values and I think it should be:
.NumberFormat = "#,##0.00,,,_);[Red](#,##0.00,,,);""-"""

Related

How to fix this error 1004? Rewrite the line

I have the following line of code in VBA:
Range("A40:A64").Formula = "=IF(index(optional_processes,row()-39)=0;"";optional_processes,row()-39))"
Without the if-statement, some cells display 0. I want these 0to be blanks. That's what the if-statement should do. I think it gives the application or object-defined error because of the double quotation marks in the statement. How can I this get blank cells instead of 0?
Even if you local Excel uses ; (semicolon) as parameter separator in formulas, when writing a formula with VBA, you have to use , (comma)
Beside this, there are some more issues with the formula:
You are missing a index at the else-part
Use """" rather than "" like Kresimir suggests
Use an ISERROR like Kiran writes in his first suggestion
I think this will work:
Range("A40:A64").Formula = "=IF(isError(index(optional_processes,row()-39)),"""",index(optional_processes,row()-39))"
Try this:
Range("A40:A64").Formula = "=IF(ISERROR(index(optional_processes,row()-39)),'',index(optional_processes,row()-39))"
OR
Range("A40:A64").Formula = "=IF(index(optional_processes,row()-39)=0,"""",index(optional_processes,row()-39))"

Range accepts sometimes only semicolons instead of commas

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)

Mystery Excel semicolon mode for data validation, stops recognizeing standard comma for unknown reason

In Excel VBA how can I set cell validation so that it works in all locales?
This code works in my locale, semicolon separated
Dim mySheet As Worksheet
Set mySheet = ThisWorkbook.Worksheets("Sheet 1")
Dim myRange As Range
Dim validValues as String
validValues = "a;b;c"
Set myRange = mySheet.Cells(2, 2)
myRange.Validation.Add _
Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=validValues
But I've seen that other locales needs comma separated
validValues = "a,b,c"
Essentially what I need is this, but I don't know how to determine 'id' in way that works in all locales.
' Internationalized delimiter
Dim id as String
id = ???
validValues = "a" & id & "b" & id & "c"
Edit:
There seems to be a "semicolon mode" of Excel that I do not understand and which I cannot reproduce reliably. I had a certain instance of Excel that got into this mode and all code run inside it worked with semicolon and not comma. I wrote a project in this instance and it worked, I would have thought I just made a mistake if not for all the code that I now have to rewrite...
Any hints in order to figure this out is appreciated.
Edit2:
After restarting Excel it changed it's mode to comma, I've been using it for a while but now this problem hit me again, Excel started using ';' (semicolon) instead of ',' (comma) as delimiter for my data validations.
This time I took a screenshot. Data validation is set to List.
Source is set to:
zero,one,both
This is the result, as you can see Excel does not care about my commas and displays all on the same line:
With source set like this it works:
zero;one;both
Result:
It is a mystery to me why Excel does this but I really need to find a way to make sure this never happens to my customer. Any help appreciated!
I have just dealed with a similar problem. I couldn't find a reason for why this happens, so I don't have a solution for good. Yet, I found a way around the problem that could be of use.
The only thing that you would need is to assign a valid value to the validated range before adding the validation.
After running your code, if the .Formula1 argument worked with semicolons, then there is no problem at all. If it didn't, the .Validation.Value property of the range returns False and you can use that as a trigger to rerun your code, replacing the semicolon separated list by a comma separated one. Then just rerun the validation.
For example:
myRange.value = "a" 'Assuming "a" is a valid value contained in the validvalues string
If myRange.Validation.Value = False Then
validvalues = replace(validvalues,";",",")
myRange.validation.modify Formula1:= validvalues
End if
Then you can clear the range value if you do not wish to have a default value shown.
I believe you are looking for a delimiter that would work on multiple scenarios (please let me know if this is not your query).
comma, semicolon, are sometimes good delimiter but often they pose serious syntax and some other string related errors .
Triple question mark ??? is also not a good choice in this case.
I prefer to go with | (the pipe) in these situations.
Sorry for the long answer :)
Microsoft says you need to use commas in VBA
https://support.microsoft.com/en-us/help/299490/data-validation-list-entries-all-on-one-line-in-excel

How to change mm/dd/yyyy to dd/mm/yyyy using VBA

I have a problem in converting mm/dd/yyyy to dd/mm/yyyy date format using VBA.
I have a table like this:
fyi, the table is auto generated from a reporting tool.
Can "string manipulation" or any excel function help? Hope anyone who know how to solve this problem can give me some idea.
Well, from the way you've worded your question I'm not convinced you actually want or need VBA.
Looking at the image you posted it would appear the first cell contains the string 05/06/2013 - 05/10/2013 not the date 05/06/2013. So the first thing you need to do is split out the parts so the built in Excel or VBA functions can convert it.
By Excel Formulas
So we could use SEARCH or FIND to find the "-" and do things dynamically. But I'm feeling lazy so I'll just assume the first 10 characters of the string are the first date and the last 10 characters are the second date. A TRIM function on the source string should make this a bit safer in case of extra spaces before or after.
So if our string 05/06/2013 - 05/10/2013 is in cell A2, we can put =LEFT(TRIM(A2),10) in B2 and =RIGHT(TRIM(A2),10) in C2.
Now these are still strings. Normally I'd use DATEVALUE to convert the strings to dates, but my copy of Excel doesn't like those crazy nonsense* date formats. So we will parse the dates into the DATE function. Putting =DATE(RIGHT(B2,4),LEFT(B2,2),MID(B2,4,2)) and =DATE(RIGHT(C2,4),LEFT(C2,2),MID(C2,4,2)) into cells C2 and D2 respectively.
From here we can recombine them using the TEXT function (much like the format function in VBA) and some string concatenation into your original single-cell date range format. Assuming that's the desired result.
So our final cell, F2, would be =TEXT(D2,"dd/MM/yyyy") & " - " & TEXT(E2,"dd/MM/yyyy"). We could of course combine all those formulas into one big mess like so:
=TEXT(DATE(RIGHT(LEFT(A2,10),4),LEFT(LEFT(A2,10),2),MID(LEFT(A2,10),4,2)),"dd/MM/yyyy") & " - " & TEXT(DATE(RIGHT(RIGHT(TRIM(A2),10),4),LEFT(RIGHT(TRIM(A2),10),2),MID(RIGHT(TRIM(A2),10),4,2)),"dd/MM/yyyy")
By Visual Basic for Applications
It's the same process here, just using VBA functions and syntax instead of Excel formulas.
Now for whatever reason the VBA version of DateValue will accept those dates in my copy of Excel. So I'll use it.
Public Function ChangeDateFormat(inputString As String) As String
Dim firstDate As Date
Dim secondDate As Date
Dim trimmedInput As String
trimmedInput = Trim$(inputString)
firstDate = DateValue(Left$(trimmedInput, 10))
secondDate = DateValue(Right$(trimmedInput, 10))
ChangeDateFormat = Format(firstDate, "dd\/MM\/yyyy") & " - " & Format(secondDate, "dd\/MM\/yyyy")
End Function
Public Sub Test()
Sheet1.[B2] = ChangeDateFormat(Sheet1.[A2])
End Sub
This can be tested either by running the provided Test sub, or ChangeDateFormat can be used as a user defined function in an excel formula =ChangeDateFormat(A2).
Note, in the date formats passed to Format, I escaped the date separator \/ instead of just putting / in. This is because the Format function will automatically replace / with the date separator from your Windows settings. And since I use a modern computer friendly date format, my seperators are dashes...
Footnote
* Life would be so much easier if people would just use ISO 8601. It exists for a reason, a good reason.

Text Format in Excel using VBA

When I use WinSQL to run a SQL statement, the result is 20100803000001812. However, when I incorporate the SQL as a macro, the result is 2.01008E+16. What should I do in the macro in order to maintain the result as 20100803000001812 ?
Thanks,
Bob
According to this article ActiveCell.NumberFormat = "#" should do the trick.
ActiveCell.NumberFormat = "0" works for me (not what I expected, but so it goes)
You might want to throw in a Cells.Columns.AutoFit to resize the columns as necessary.