Error with Format function - excel

I am having a problem with the Format() function in excel vba. I am trying to alter the formatting of a date formatted cell to change the way it is displayed. However, everytime i invoke Format to do that i get the error: "Compile Error: Wrong number of arguments or invalid property assignment."
here is the code:
Sub test()
Dim given
given = DateSerial(2012, 10, 11)
dateformat = Format(given, "dd/mm/yy")
MsgBox given & vbCrLf & dateformat
End Sub
This is just a test function and should function on its own and return "11/10/12". This code works on other computers. What could be wrong?

Had this problem with code I put in a Worksheet_Activate() today and was pulling my hair out. Resolved it by changing Format to VBA.Format
So try:
Sub test()
Dim given
given = DateSerial(2012, 10, 11)
dateformat = VBA.Format(given, "dd/mm/yy")
MsgBox given & vbCrLf & dateformat
End Sub

This is because you might also have some Sub named Format somewhere else in your project.Hence you get the error.

Currently you are declaring your given variable as a variant by default. Please declare it as Date data type. And to be safe, make sure you only send a Date using CDate() into the Format() to format as the date style you want.
Also DateSerial input should be in the following format. Which in your case alright. ;)
DateSerial(CInt(x), CInt(y), CInt(z)
Code snippet:
OPTION EXPLICIT '------------ please add this to your code to begin for better coding
Sub test()
Dim given as Date '-------- define given as Date type
Dim dateformat as Date
given = DateSerial(2012, 10, 11)
dateformat = Format(CDate(given), "dd/mm/yy") '--------- anyway wrap with CDate() to be sure
MsgBox given & vbCrLf & dateformat
End Sub

Related

Convert date to string for automated directory searching

My ultimate goal is to be able to search a file path, where another user will be creating a new folder each month (for example next month the user will create the folder "January 2022"), and I need to be able to search for that folder in an automated way based on the current month and year.
My plan is to create a string object like so:
Dim strDirectory As String
strDirectory = "C:\foo\bar\baz\" & strCurrentMonthName & " " & strCurrentYear
But, I'm having trouble extracting the year as text. Originally I tried to do this:
Dim TestMonth As String
Dim TestYear As String
TestYear = Year(Now)
TestMonth = GetMonthName(Format(Now, "mm"))
Problem is that testYear gets returned as 7/13/1905. This webpage shows how to fix this error in a spreadsheet, but that's not going to help my situation as the date will never be pulled from a spreadsheet (as I feel that's a very error-prone way to do things). The Year function supposedly only works on Variant, Numeric, or String expressions and I don't know how to get just the year from Now.
Keep in mind that my ability to access standard libraries is very limited, I'm using an older version of Excel (2016) and have no control over packages or updates (there are certain features I've had to do without such as MonthName() for example, I had to create my own version of that)
Format returns a Variant (String) containing an expression formatted according to instructions contained in a format expression.
So whatever format you express in Format will be returned as a string.
Public Sub Test()
Dim CurrentDate As Date
CurrentDate = Date
Dim strDirectory As String
strDirectory = "C:\foo\bar\baz\" & Format(CurrentDate, "mmm yy") '"C:\foo\bar\baz\Dec 21"
strDirectory = "C:\foo\bar\baz\" & Format(CurrentDate, "mmmm yyyy") '"C:\foo\bar\baz\December 2021"
End Sub
No need for a GetMonthName function - Format(Now(),"mmmm") returns December this month.
Figured it out:
Dim TestMonth As String
Dim TestYear As Date
testYear = Now
TestMonth = GetMonthName(Format(Now, "mm"))
Range("A1").Select
ActiveCell.FormulaR1C1 = "C:\foo\bar\baz\" & TestMonth & " " & Year(TestYear)
Output:
C:\foo\bar\baz\December 2021

Using the Date variable in different formats within one module

I am trying to set today's date and use it in different formats for various tasks, but I have no idea how to go about it. I know that Date is a global variable but it is in 2017-12-19 format on our system, for some tasks I'd need it to be mm-dd-yyyy or just mm-dd but I don't know how could I set this up without prompting the user to manually enter the date in said formats. Also can I use the Date variable just like a string or do I need to convert it?
Sub BasedOnDate()
Dim filename As String, Source As String, Destination As String
Dim myValx As String
Dim myVal1 As Date
Dim myValn As Date
Dim myFile As String
Dim myPath As String
'trying to declare today's date, but just the month and day as "mm-yy"
myVal1 = Date("mm-yy")
myValn = Replace(myVal1, "-", "\")
'trying to declare the date here in the desired format
myValx = Date("mm-dd-yyyy")
'File paths
Source = "\\Rdcicgtcuwd01p\app_log\36196_WMS\WMS_36196_PROD_" & myValx & ".csv"
Destination = "\\olscmesf003\gcm_emea\TCU_REPORTS\APPS\Reports\Regional\Workflow Management System\2017\" & myValn
FileCopy Source, Destination
End Sub
You could use Format() function:
myValx = Format(Date, "mm-dd-yyyy")
Tip: Please keep in mind that Format() returns string, here it works fine, but could be a problem in other situation.

Macro works on every computer except one where it gives "1004 error"

Disclaimer: I've read the relevant questions/answers regarding Error 1004 and I couldn't find a solution.
I have a macro that I distributed within the team and it works perfectly on all computers (including mine) except one. She's running the same version of Excel on the same system and she can use other macros except this one, I get the "Error 1004 SaveAs function failed" message. It is by a very long shot but did I miss some security setting or is there some problem with the code that could cause this? This is the code in question:
Sub PSSaveFile()
Dim myVal2 As Variant
Dim myValn2 As String
Dim myDate As String
Dim mFilePath As String
myVal2 = InputBox("Please enter today's date in mm-dd format")
myValn2 = Replace(myVal2, "-", "\")
myDate = Date
mFilePath = "\\xxxxxxxx003\xxx_emea\TCU_REPORTS\APPS\Reports\Regional\xxxxx for PC Web xx\2017\" & myValn2
ActiveWorkbook.SaveAs FileName:=mFilePath & "\xxxRHLogs-" & myDate & "_checked"
End Sub
Let me guess - the guy with the other computer is from another country, thus using his own regional settings on the PC. Thus the date format is a bit fancier, e.g. dd/mm/yyyy and it is not allowed to save it as a file because of this.
Try to change the date like this:
myDate = year(date) & month(date) & day(date)
and try again. This would eliminate the fancy settings part.

How to convert string to Workbook name in VBA

Sub openwb()
Dim x260path As String
x260path = "E:\sarath\PTMetrics\20131002\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_" & Format(Date, "YYYYMMDD") - 1
Workbooks("x260path").Activate
ActiveWorkbook.SaveAs ["E:\sarath\PTMetrics\20131002\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_" & Format(Date, "YYYYMMDD")]
Debug.Print x260path
End Sub
Here, when i execute, an error says "subscript out of Range". And it appears on 4th line.when i use 'workbook' to declare 'x260path' instead of string, It shows another error saying "Object variable or with block variable not set" on line 3. Can u help?Why is this happening?
In VBA the equivalent function to =Today() is Date() (*or Date)
x260path = CONCATENATE("..." & Date)
Alternatively, use Now() function ( that includes a time stamp as well though )
x260path = CONCATENATE("..." & Now)
debug.print Date
02/10/2013
and
debug.print Now
02/10/2013 08:39:20
some of the spreadsheet functions are available to use with the WorksheetFunction class. For example
Sub Main()
Dim sum As Double
sum = WorksheetFunction.sum(10, 20)
MsgBox sum
End Sub
Note: when you type the sum = WorksheetFunction. as soon as you type in the . you should get the VBA's Intelli-sense help. It is a list of all available functions you can use with the WorksheetFunction class.
In your case the =Concatenate function is equivalent to & operator in VBA. Therefore the easiest way would be to join two string using the &
x260path = "C:\..." & date
If a function you are trying to use doesn't exist in the Intelli-sense you can create your own UDF or you can do some online research on how the function works and how to overwrite it.

OpenOffice Macro to Access Contents of a Table

I wrote a Macro, which should take two Dates (dd.mm.yyyy) as a String from a table in an OpenOffice Document (Writer, not Calc). These two Dates should be merged to this:
ddmmyyyy-ddmmyyyy. This should be used as the filename then.
The Table has only one row and 6 columns, the first Date being in table2:D1:D1 and the second one in table2:F1:F1.
I "translated" this to table2(1, 4) and table2(1, 6)
This German site is doing what I want to do, but with spreadsheets in a OOCalc Document and not OOWriter.
Enough talk, here is my code:
sub save
oDoc=thisComponent
sStartDate = oDoc.Table2(1, 4)
sEndDate = oDoc.Table2(1, 6))
sFilename = sStartDate.String & sEndDate.String
sURL = ConvertToURL("file:///home/cp/Documents/" & sFilename & ".odt")
msgbox sURL
' oDoc.StoreAsURL(sURL, Array())
end sub
Yes, I run linux, so the path should be correct.
When I try to run this script it says:
Property or Method not found table2
I of course tried google but somehow I could not find a solution. A hint in the right direction could be enough, I also guessed I have to write "more":
sStartDate = oDoc.getString(table2(1, 4))
or something similar. Didnt work either. Another thing I tried was using (0, 3) instead of (1, 4).
Well I would appreciate it, if someone could help me a bit! :)
And I hope I have done everything right how I posted here.
Vaelor
EDIT:
I have now modified the script to this, according to the PDF found HERE in chapter 14.9.
It now looks like this,
sub save
oDoc=thisComponent
Dim oTable
Dim sTableName As String
sTableName = "Table2"
oTable = oDoc.getTextTables().getByName(sTableName)
' oTable = oTables.getByName(sTableName)
sStartDate = oTable.getCellByPosition(0, 3)
sEndDate = oTable.getCellByPosition(0, 5)
sFilename = sStartDate.String & sEndDate.String
sURL = ConvertToURL("file:///home/cp/Documents/" & sFilename & ".odt")
msgbox sURL
' oDoc.StoreAsURL(sURL, Array())
end sub
But, still not working. Now I get this exception IndexOutOfBoundsException.
(I wanted to link it, but it says, I cant post more than 2 links :-( )
My first thought was I had to change the cels to 0, 3 and 0, 5. After changing that, the error still occurs. :-(
Edit2:
Since I got no response, I think I will try this in Python, maybe it yields better results.
This code demonstrates how to locate a text table with the given name and how to access individual cells.
function get_table_by_name(name as string) as object
dim oenum as object
dim oelem as object
oenum = thisComponent.text.createEnumeration
while oenum.hasMoreelements
oelem = oenum.nextElement
if oelem.supportsService("com.sun.star.text.TextTable") then
if oelem.Name = name then
get_table_by_name = oelem
exit function
end if
end if
wend
end function
Sub Main
dim table as object
table = get_table_by_name("Table1")
if not isNull(table) then
msgbox "Got " & table.Name & " " & table.getRows().getCount() & "x" & table.getColumns().getCount()
msgbox "Cell[0,0] is " & table.getCellByPosition(0, 0).getString()
end if
End Sub

Resources