Create directory without compile error message - excel

Please help. I am pretty new. I am trying to create a folder using dates and got a compile error message "wrong number of arguments or invalid property assignments". The code worked perfectly for a month but not anymore.
Sub Test()
MkDir "\\AD.TEST.COM\nas\Team-AB-TEST\TEST FOLDER\TEST FOLDER \" & Format(Date, "yyyy") & " Email Tracking\" & Format(Date, "mm.dd.yy") & "\Attach\"
End Sub

Your code is compiling perfectly.
But when you add this next to your code:
Function Format(s As String)
Format = "tralala"
End Function
Then, it does not work anymore.
Can you verify you don't have some Format() function defined somewhere?

Related

Saving excel xlsm file not working due to error

I have this macro which is updating some tables and it has been working fine for the past two weeks, however it suddenly started giving me 1004 runtime error - initially it was runtime error 1004 method saveas of object _workbook failedub SaveAs(), now it is simply Run Time Error 1004 “Application-Defined or Object-Defined Error.
I suspect is has something to do with saving the file as that's the point it gives me error, everything else works fine. I have separated the saving code in a different macro and its still giving this error.
I have tried to make the path string into one piece (Mth var is a variable we change each month of reporting and is fed off a sheet value but have had to add it manually for testing purpose). Initially Path and Filename missed the ("S") at the end as I thought the names might be conflicting with something in the library.
Please note, before the code was using ActiveWorkbook.Saveas and was working fine I am not sure it's a problem of Excel knowing which sheet or workbook to look at.
How do I fix this? Please see code below:
ThisWorkbook.Activate
Dim Mth As Integer
Mth = 4
Dim FileNames As String
Dim Paths As String
Dim Fullstring As String
Application.DisplayAlerts = False
Paths = "\\RL1VMFIL02\Finance$\Financial Management\SITES & SERVICES\Corporate\2020-21\C - Statements & Trends" & "\M" & Mth & "\"
FileNames = Format(Now(), "dd.mm.yy") & " Budget Statement & Trend M" & Mth & " - " & Format(Now(), "hh.mm") & ".xlsm"
Fullstring = Paths & FileNames
ThisWorkbook.Activate
ThisWorkbook.SaveAs Fullstring
Application.DisplayAlerts = True
End Sub
This has been fixed by making sure the path folder exists as adviced by #RustyBucketBay & #GMalc.
Explicitly, the Month path included a 0 so it should've been either Mth var = '04 rather than 4 or path "\M0" & Mth & ""
Many thanks guys for the help!

vba excel scrip for attachments failure

enter image description hereenter image description hereI have just tried it with the modified code but unlucky it is still not working. So let me clearify my question further:
I have the pdf file
Risikomanagement-Report Pfandbrief Hypothekenpfandbrief 20180706.pdf
in the Folder:
T:\30_Deckungsstock\Deckungsnachweise\tgl.RMR
My aim is to grap this typ of file (with the current date) and attache it to an E-Mail.
My code for this goes as following:
.Attachments.Add "T:\30_Deckungsstock\Deckungsnachweise\tgl.RMR\Risikomanagement-Report Pfandbrief Hypothekenpfandbrief" & Format(datDatum, "YYYYMMDD") & ".pdf"
Issue: It can't find the file. I am pretty sure there is a small bug which I couldnt spot.
The msgbox states: the file cannot be found. Please check the path and the name of the file
Edit: The file exists:enter image description here
Try
Attachments.Add "T:\30_Deckungsstock\Deckungsnachweise\tgl.RMR\Risikomanagement-Report Pfandbrief Hypothekenpfandbrief " & Format$(datDatum, "YYYYMMDD") & ".pdf"
Note there is a space before the date part.
Edit:
Use
debug.print "T:\30_Deckungsstock\Deckungsnachweise\tgl.RMR\Risikomanagement-Report Pfandbrief Hypothekenpfandbrief " & Format(datDatum, "YYYYMMDD") & ".pdf"
to get the filepath being used and verify whether correct.
The current error is because you are not assigning a value to datDatum before using it. The default initialized value is being used.
If you don't assign datDatum an initial value it will be initialized as 00:00:00. When you apply the Format function it gets converted to 18991230
You can verify with the following:
Option Explicit
Public Sub test()
Dim datDatum As Date
MsgBox Format$(datDatum, "YYYYMMDD")
End Sub
You will see 18991230 appear.
Solution is to assign a value to datDatum e.g.
datDatum = Now

Accurately debugging a called Userform in VBA excel 2016

I was wondering whether there is a smarter/more accurate method of debugging userform initializations in VBA that are called from a specific module.
Because when I write an erroneously piece of code in the Userform_initialisatize, I the error I receive states an error, but not where it occurs, the highlighted piece of code is simply call Userform_intitialize and I'm left guessing which piece of code in Sub Userform_intitialize contains the error.
So incrementally building a userform with test runs after every small addition of code work effectively to create a stable Userform initilisation code. Because I know what I changed since the last successful run, but it would save quite some time if I immediately know where the error occurs, especially in cases where trial runs consume a lot of time.
So are there ways to extract in which line the exact error occurs within a called Sub Userform_intitialize in vba Excel 2016?
As #A.S.H already mentioned the handler of Initialize event should remain private. Thats because the Initialize event itself is private so it is intended to be handled by the instances itself and not by anybody else.
So are there ways to extract in which line the exact error occurs within a called Sub Userform_intitialize in vba Excel 2016?
Regarding your question, yes it is still possible to extract the line number where the error occurred. But the lines needs to be part of the source code. Then the function VBA.Information.Erl can be used to get the line number. Example:
UserForm module
Option Explicit
Private Const MODULE_NAME As String = "MyUserForm."
Private Sub UserForm_Initialize()
On Error GoTo Error_In_UserForm_Initialize
1 Const procName As String = "UserForm_Initialize"
' Some code here
2 Dim d As Date
3 d = Now
4 MsgBox "Hi from my userform! 'Now' is '" & d & "'", vbInformation, "Info"
' Here error occures, max. value of Integer is 32.767
5 Dim i As Integer
6 i = 40000
7 Exit Sub
Error_In_UserForm_Initialize:
8 Dim errorDescription As String
9 With Err
10 errorDescription = "Error '" & .Number & "'" & _
" with description '" & .Description & "'" & _
" occured in procedure '" & MODULE_NAME & procName & "'" & _
IIf(Erl <> 0, " on line '" & CStr(Erl) & "'.", ".")
11 End With
12 MsgBox errorDescription, vbCritical, "Error"
End Sub
Some additional readings about Erl here or here.

Save As method is creating runtime error for some users not others

I created a command button that auto saves the workbook into one of two file paths depending on info in the spreadsheet. This works fine for me but my colleague is gettting the follwing error everytime.
The method is extending the file path and adding \0BA1700 in this instance (this changes every time). This doesn't happen on my computer and the code works as it should. Here is the sub:
Private Sub CommandButton21_Click()
Dim pathUnder As String
Dim pathOver As String
Dim file As String
file = Range("D2").Value
pathUnder = "G:\Technical Services\LARGE CORPORATE UW\Full Insurance\FI Quote Spreadsheets (below 500)\"
pathOver = "G:\Technical Services\LARGE CORPORATE UW\Full Insurance\FI Quote Spreadsheets (above 500)\"
If Range("D4").Value = "" Or Range("D2").Value = "" Then
MsgBox ("Save Failed. Please ensure there are values in both cells D2 and D4")
Else
If Range("D4").Value >= 500 Then
ActiveWorkbook.SaveAs fileName:=pathOver & file & ".xlsm", FileFormat:=52
Else
ActiveWorkbook.SaveAs fileName:=pathUnder & file & ".xlsm", FileFormat:=52
End If
End If
End Sub
Help much appreciated.
Maybe some kind of exception? Are you sure nothing is currently using this file? Maybe you own program does?
Solved. My colleague's computer didn't have the G drive mapped to the correct server so remapped it and now working fine.

Error with Format function

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

Resources