Excel : Date format issue - excel

I have few cells where I fill date in those using 'FormatDatetime' function,
code:
Range("AX1") = FormatDateTime((Docx.getAttribute("r1ed")))
Range("AX2") = FormatDateTime((Docx.getAttribute("r2ed")))
Range("AX3") = FormatDateTime((Docx.getAttribute("r3ed")))
Range("AX4") = FormatDateTime((Docx.getAttribute("r4ed")))
If date is separated by "." all the cells would show like "12.1.2013",but if I change my system date format separated by "-","AX4" shows date as still "12.1.2013".but other shows correctly.
I need to have fix for this,since I use these dates' for calculation later in VBA.
Please suggest some answers.

I think your problem is that FormatDateTime() returns a string, change it to DateValue() instead. If the return from Docx.getAttribute() contains dots you'll need to replace them with slashes first.
So;
'[AX1] is the same as Range("AX1")
[AX1] = DateValue(Docx.getAttribute("r1ed"))
[AX2] = DateValue(Docx.getAttribute("r2ed"))
[AX3] = DateValue(Docx.getAttribute("r3ed"))
[AX4] = DateValue(Docx.getAttribute("r4ed"))
Or, if there are dots;
[AX1] = DateValue(Replace(Docx.getAttribute("r1ed"), ".", "/"))
[AX2] = DateValue(Replace(Docx.getAttribute("r2ed"), ".", "/"))
[AX3] = DateValue(Replace(Docx.getAttribute("r3ed"), ".", "/"))
[AX4] = DateValue(Replace(Docx.getAttribute("r4ed"), ".", "/"))
If this doesn't solve the issue, can you please post more info about what Docx.getAttribute() is returning please.
Edit: Also, knowing the format you need the cells to contain would be helpful - I'm assuming proper dates will be acceptable - You might need a string with a date in a certain format. If that's the case you could wrap the above with something like;
[AX1] = Format(DateValue(Docx.getAttribute("r1ed")), "dd/mm/yyyy")
It might be that FormatDateTime() is betraying you, Format() might be more flexible

Related

Setting Number Format to Accounting in VBA

With ActiveSheet
.Range("T26:T31").NumberFormat = "_(£* #,##0.00_);_(£* (#,##0.00);_(£* " - "??_);_(#_)"
I am trying to set the format of a cell range to Accounting, I have looked at the number format (above) and tried setting it to that, but I get a Type Mismatch.
I also tried doing Debug.Print Application.ActiveCell.NumberFormatLocal to find out how excel reads it, copied that in and still with no luck.
Anyone got any ideas?
You need to double any quotation marks inside the format code, so:
.Range("T26:T31").NumberFormat = "_(£* #,##0.00_);_(£* (#,##0.00);_(£* "" - ""??_);_(#_)"

Excel VBA extract date from CSV txt

I'm having trouble extracting this text, exactly as it appears, from a CSV. There are similar questions posted on SO but they don't match my requirements:
I want to extract "31 January 2017" from this row:
4,'31 January 2017','Funds Received/Credits',56,,401.45,
Currently, VBA considers it "31 Jan" without the year. I've tried applying .NumberFormat to the cell (general, text, date).
SOLUTION REQUIREMENTS:
No user action required -- Interact with the file only using VBA (not using File > Import > Wizard)
Compatible with VBA Excel 2003
Extract the full text regardless of Excel or operating system date settings
Thank you for your ideas
You can use the split function, using the comma as a delimiter like this:
sResult = Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1)
If you dont want the single quotes, then add the replace function like this:
sResult = Replace(Split("4,'31 January 2017','Funds Received/Credits',56,,401.45, ", ",")(1), "'", "")
If you include the "Microsoft VBScript Regular Expressions 5.5" Reference, you can set up a pattern that will extract the whole date if it is found. For example:
Dim tstring As String
Dim myregexp As RegExp
Dim StrMatch As Object
tstring = 'Line from the CSV, or entire CSV as one string
Set myregexp = New RegExp
myregexp.Pattern = "\d{1,2} [A-Z]{3,9} \d{4}"
Set StrMatch = myregexp.Execute(tstring)
You get the benefit from this method that all the dates in the CSV will be pulled out at once, much faster than using a split line by line. Additionally, the dates may be accessed by using
DateStr = StrMatch.Item(index)
for the whole string line, or substrings can be set up to get specific parts of the string(Such as month, day, year).
myregexp.Pattern = "\(d{1,2}) ([A-Z]{3,9}) (\d{4})"
Set StrMatch = myregexp.Execute(tstring)
DateStr = StrMatch.Item(index1).SubMatches(index2)
It is a very powerful tool, with a simple set of symbols for development of patterns. I highly suggest you familiarize yourself with it for manipulation of large strings.

Getting Cell as String in PHPExcel by column and row

I am trying to read a cell with possible trailing zeros as a string instead of numeric (which strips off leading zeros). The cell is read by integer column/row as below instead of column string as this answer has.
initial code
$instReader = $reader->load($this->file);
$sheet = $instReader->getSheet(0);
I tried modifying this from:
$keyCell = $sheet->getCellByColumnAndRow(1,5);
to:
$sheet->setCellValueExplicitByColumnAndRow(1,5, PHPExcel_Cell_DataType::TYPE_STRING);
$keyCell = $sheet->getCellByColumnAndRow(1,5);
the former gives 1407 for $keyCell instead of 01407
the latter gives "s" or ""
how do I treat the cell as string before calling getCellByColumnAndRow and using only integer values for column and row.
(BTW, if this can be done once for an entire column instead of each time for each individual cell that would be better)
$keyCell = $sheet->getCellByColumnAndRow(1,5)->getValue();
Will read the cell data in the format that it's actually stored by Excel, you can't arbitrarily change that or tell PHPExcel to read it as a different datatype.
However, if the cell has formatting applied, then you can use
$keyCell = $sheet->getCellByColumnAndRow(1,5)->getFormattedValue();
instead, and this will return the data as a string, with whatever format mask was defined in the Excel spreadsheet
Same issue for me. I become crazy.
Tried to set
$objReader->setReadDataOnly(true);
wasn't working
tried
$sheet->getCellByColumnAndRow(4,$row)->getValue()
because normaly display text as raw => doesn't working.
So last I change code in library. Edit file named DefaultValueBinder.php
Search for dataTypeForValue function and set this :
} elseif (is_float($pValue) || is_int($pValue)) {
return PHPExcel_Cell_DataType::TYPE_STRING;//TYPE_NUMERIC patch here;
} elseif (preg_match('/^\-?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)$/', $pValue)) {
return PHPExcel_Cell_DataType::TYPE_STRING;//TYPE_NUMERIC patch here;
So now return numbers with 0

Format a date into mm.dd.yyyy format

I have a VBA script in which I am trying to convert the string in "yyyymmdd" format to "mm/dd/yyyy" format. However, when I incorporate format function to achieve this, it's showing
"Run time error-6": Overflow
Can any one help me with this ? The following is the correspondig VBA code.
// NewDate is in the format "yyyymmdd" being extracted out of a file path like "C:\Files\20140611\file.csv"
Required_format=Format(NewDate,"mm/dd/yyyy") // This line shows the error
you will have to format this yourself, because Format doesn't know that it is dealing with a date, it simply sees a string.
Use something like (psuedo code):
y = left(NewDate, 4)
m = mid(NewDate, 5, 2)
d = right(NewDate, 2)
Required_format = m + "/" + d + "/" + y
Just be absolutely sure the format is consitant. Any change (especially the padding is notorious) messes up your format.
Here is one more solution:
CDate(format(NewDate,"mm dd yyyy"))
Here's another method. As you wrote above, NewDate contains an 8 digit string representing a date in yyyymmdd format. The following "one liner" will output a date (as a string) in your desired format:
Format(Format(NewDate, "####/##/##"), "mm/dd/yyyy")

Format a cell as arbitrary currency regardless of locale, using VBA

This is really bugging me as it seems pretty illogical the way it's working.
I have a macro to format a cell as a currency using a bit of code to obtain the currency symbol.
Here is the code involved:
Dim sym As String
sym = reportConstants(ISOcode)
'Just use the ISO code if there isn't a symbol available
If sym = "" Then
sym = ISOcode
End If
With range(.Offset(0, 3), .Offset(3, 3))
.NumberFormat = sym & "#,##0;(" & sym & "#,##0)"
Debug.Print sym & "#,##0;(" & sym & "#,##0)"
End With
reportConstants is a dictionary object with currency symbols defined as strings. E.g. reportConstants("USD") = "$". This is defined earlier in the macro.
When the macro runs it gets the ISO code and should then format the cell with the corresponding currency symbol.
When I run it in one instance the ISO code is "USD" - so sym is defined as "$" - but it still formats the cell with a pound sign (£). When I debug.print the format cell string it shows $#,##0;($#,##0) so, as long as I got my syntax correct, it should use a dollar sign in the cell. But it uses a £ sign instead. (I am running a UK version of excel so it may be defaulting to £-sign, but why?)
Any help greatly appreciated.
I just recorded a macro to set the format to $xx.xx and it created this: [$$-409]#,##0.00. Looks like the -409 localises the currency to a particular country; it works without it - try changing yours to .NumberFormat = "[$" & sym & "]#,##0.00"
Btw guess I read your question somewhat after posting ;) Excel is well influenced by the regional settings of your computer for currency, language, dates... Using numberformat can force it to keep the sign you require. if it is a matter of rounding up you can try to: On Excel 2010, go to File - Options - Advanced and scroll down to "When calculating this workbook" and click on the "set precision as displayed" and OK out. 
Try this: given your values are numerics/ integers/decimals....
Range("a2").Style = "Currency"
Or you can use format:
Format(value, "Currency")
Format(Range(a2).value, "Currency")
References:
http://www.mrexcel.com/forum/excel-questions/439331-displaying-currency-based-regional-settings.html
http://www.addictivetips.com/microsoft-office/excel-2010-currency-values/
(PS: I am on mobile, you may try these two links)

Resources