I am getting a weird problem in Access 2007 SP3. When I export a report to pdf I get the "Output To" prompt which I don't want, is there anything in my code I am doing wrong?
OverViewFile = DLookup("ExportPath", "dbo_Defaults") & "PC" & Format(Now(), "ddmmyy") & Format(Now(), "hhmm") & ".pdf"
DoCmd.OutputTo acOutputReport, "Rpt_ExportBPC", acFormatPDF, OverViewFile, False
If I've missed anything please let me know.
I don't get that prompt from Access 2007 SP3 when adapting your OutputTo with the name of my report object and giving it a valid file path for OverViewFile. So I suspect your problem is due to OverViewFile; inspect the value of that string:
OverViewFile = DLookup("ExportPath", "dbo_Defaults") & "PC" & Format(Now(), "ddmmyy") & Format(Now(), "hhmm") & ".pdf"
Debug.Print OverViewFile
DoCmd.OutputTo acOutputReport, "Rpt_ExportBPC", acFormatPDF, OverViewFile, False
You can view the output from Debug.Print in the Immediate window (Ctrl+g will take you there).
Perhaps DLookup is returning Null. You would then have a valid VBA string for OverViewFile, but it would not be a valid Windows path.
There is another issue with OverViewFile which probably doesn't contribute to the problem, but I'll suggest this because it's simpler and I think you actually want hhnn instead of hhmm in the file name (n represents minute; m represents month)
OverViewFile = DLookup("ExportPath", "dbo_Defaults") & "PC" & _
Format(Now(), "ddmmyyhhnn") & ".pdf"
Related
Does anyone know if and how i can print a PDF from Access and secure it with a digital ID? I can print to PDF on buttonclick, but now i want to secure it in the same step. This means that i need to get up the Sign with digital ID box when i export to PDF form my access file, but how is that done?
I have the following working code for printing
Filnavn = mappe & Me.IDAarstallLNr & " DOC" & " - " & Replace(Now(), ":", "") & ".pdf"
Me.txtFilnavnDigitaltSignertPDF = mappe & Me.IDAarstallLNr & " Signed date " & Replace(Now(), ":", "") & ".pdf"
DoCmd.OutputTo acOutputReport, Rapportnavn, acFormatPDF, Filnavn, True, , acExportQualityScreen
If pfUserName() <> "SGR" Then Me.File_Dato_Mappe = Date
DoCmd.RunCommand acCmdSaveRecord
End Sub
I want to export a query as a text file from an access database but using vba. The issue is I need to save it with .ail2 in the name.
basically I want it of the form: "currentdate_version.ail2".txt (the quotations are very important otherwise it won't work).
So for example todays first version would look like:
"20182910_1.ail2".txt
I have tried exporting it manually and saving it as this but the export wizard doesn't seem to like the quotation marks in the saved name. I have therefore been exporting it (using a custom saved export that i've labelled test1 - it includes the headers of each column, sets the text qualifier as 'none', the field delimiter as 'tab' and file format is 'delimited').
I am using the following code in access, the first part just makes sure the folder with the current date exists.
Private Sub ExportExcel()
Dim myQueryName As String
Dim myExportFileName As String
Dim strSheets As String
Dim sFolderPath As String
Dim filename As Variant
Dim i As Integer
strSheets = Format(Date, "yyyymmdd")
sFolderPath = "M:\AIL2Files\" & strSheets & ""
Dim fdObj As Object
Set fdObj = CreateObject("Scripting.FileSystemObject")
If fdObj.FolderExists("" & sFolderPath & "") Then
Else
fdObj.CreateFolder ("" & sFolderPath & "")
End If
i = 1
filename = Dir(sFolderPath & "\*" & i & ".txt")
Do While Len(filename) > 0
filename = Dir(sFolderPath & "\*" & i & ".txt")
i = i + 1
Loop
myQueryName = "001_querytest"
myExportFileName = "" & sFolderPath & "\" & Chr(34) & "" & strSheets & "_" & i & ".ail2" & Chr(34) & ".txt"
DoCmd.TransferText acExportDelim, "test1", myQueryName, myExportFileName, True
End Sub
test1 isn't being picked up even though its a 'saved export'. I assume I'm doing this part wrong... but even still I reckon the save won't be successful and will not include the quotation marks.
Thanks.
EDIT:
I have tried doing the following instead:
DoCmd.TransferText transferType:=acExportDelim, TableName:=myQueryName, filename:=myExportFileName, hasfieldnames:=True
It now saves, but again not including the quotation marks as desired. Whats interesting is when I type ?myExportFileName in the immediate window, it displays my desired filename but the command is clearly not working correctly as I get it of the form:
_20181029_1#ail2_
Instead...
Here is image if I use save as:
I end up getting:
There are some misconceptions here.
Windows file names cannot contain double quotes ", period. And you don't need them, either. Just save your file as filename.ail2.
This is what you get when doing "Save as". Tell Explorer to show file extensions, and you'll see that you don't have "filename.ail2".txt but filename.ail2.
You only need
myExportFileName = sFolderPath & "\" & strSheets & "_" & i & ".ail2"
test1 isn't being picked up even though its a 'saved export'.
DoCmd.TransferText doesn't use saved exports, but export specifications. See here for the difference:
Can I programmatically get at all Import/Export Specs in MS Access 2010?
Addendum
DoCmd.TransferText could throw a runtime error when given an illegal file name, but apparently it tries to save the day by exchanging the illegal characters by _, hence _20181029_1#ail2_ (.txt)
A workaround to this is first saving the file as a .txt using DoCmd.TransferText, but running a shell and renaming. Like such:
myExportFileName = sFolderPath & "\" & strSheets & "_" & i & ".txt"
DoCmd.TransferText TransferType:=acExportDelim, SpecificationName:="034_AILFILE Export Specification", TableName:=myQueryName, filename:=myExportFileName, HasFieldnames:=True
Set wshShell = CreateObject("Wscript.Shell")
strDocuments = wshShell.SpecialFolders("M:\AIL2Files\" & strSheets & "")
oldFileName = myExportFileName
newFileName = sFolderPath & "\" & strSheets & "_" & i & ".ail2"
Name oldFileName As newFileName
There is undoubtedly cleaner ways of doing this but I imagine that this method could be used to save any files that have non traditional extensions, but fundamentally follow the format of a .txt file.
I would like to ask you for help with (edited) VBA code I found while searching for solution. My goal is to add validation rule to multiple field of table at once by VBA code. I have to use VBA code because there is so many fields and manual input would be insane.
Validation rule: NOT LIKE "*"+Chr(10)+"*" OR "*"+Chr(13)+"*" OR "*"+Chr(9)+"*"
(user can't save "enter", "ctrl+enter" and "tabulator")
For using this rule in VBA function the syntax is quite different but input to MS Access is correct.
My VBA code (not directly my, I found it and edit to my needs)
Public Function SetFieldValidation()
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim strValidRule As String
Dim strValidText As String
Dim bytNumOfFields As Byte
strValidRule = "NOT LIKE " & Chr(34) & "*" & Chr(34) & "+Chr(10)+" & Chr(34) & "*" & Chr(34) & " OR " & Chr(34) & "*" & Chr(34) & "+Chr(13)+" & Chr(34) & "*" & Chr(34) & " OR " & Chr(34) & "*" & Chr(34) & "+Chr(9)+" & Chr(34) & "*" & Chr(34)
strValidText = "Some error msg"
Set dbs = CurrentDb
Set tdf = dbs.TableDefs("Table_Name")
For bytNumOfFields = 0 To tdf.Fields.Count - 1
With tdf.Fields(bytNumOfFields)
If .Name <> "Record ID" Then
.ValidationRule = strValidRule
.ValidationText = strValidText
End If
End With
Next
End Function
In the past this script works with rule NOT LIKE "*"+Chr(10)+"*" OR "*"+Chr(13)+"*".
Than tried to add OR "*"+Chr(9)+"*".
Since this modification the MS Access (VBA) returns error: Property value is too large. (Error 3309) while I run the script. When I tried return to previous version of script without +Chr(9)+, the error still remains (even I succesfully used this script in the past and validation rules are set in another tables).
I'm really beginer in VBA, honestly I only need to setup this rule to all field of all tables. Can someone experienced tell me what's wrong in the code?
Thank you very much.
I suggest not using Chr(). Since Chr will always return the same value for a particular number, e.g. Chr(65) always returns A, I don't think you need to use the function to get the value you want. So try setting your strValidRule as one long static string with the characters returned by the Chr() functions hard coded.
I did a research and probably the problem is somewhere else - looks like error in table design of specific table.
1.) First test: At first I tried to debug strValidRule string and compare two approaches for string (my and with quotes as #Rominus advised). The results are same but quoString is smoother approach. Than I run script (tried both approaches). Error msg said 'Property Value Too Large' error 3309 and the old valid rules remains in table design unchanged (rules were set in the past and remains).
Sub teststring()
chrString = "chrString: NOT LIKE " & Chr(34) & "*" & Chr(34) & " +Chr(10)+ " & Chr(34) & "*" & Chr(34) & " OR " & Chr(34) & "*" & Chr(34) & " +Chr(13)+ " & Chr(34) & "*" & Chr(34)
Debug.Print chrString
quoString = "quoString: NOT LIKE ""*"" +Chr(10)+ ""*"" OR ""*"" +Chr(13)+ ""*"""
Debug.Print quoString
End Sub
2.) Second test: From my script above I firstly 'commented' values of strValidRule and strValidText by ' and add empty values "". Script run without error msg and added empty values.
Than I 'uncommented' the values and run script with values mentioned above (quoString approach and some msg for strValidText). Scritp run with error msg 'Property Value Too Large' error 3309. BUT, when I checked table design, the valid rules were properly set and working even the error msg popped up.
3.) Third test: I tried to use script in another table and run it without previously adding empty values described in step 2. (because in table were set old valid rules too). Script successfully overwrote old valid rules by new ones without msg of error 3309.
So, I found the way how to set valid rules but there is still some bug that shows error msg in specific table. Don't know how to fix it but I hope it haven't affect of my main goal (setting new working valid rules).
I am currently in the process of generating a report in access which, once generated, should be saved to a save location to user puts in.
Here's my block of code.
ReportName = "Appraisal_" & Trim(Str(Year)) & "_" & Me.empnr & "_" & Veilig(Me.empnr) & "_" & Format(Now(), "YYYY_MM_DD_HH_MM_SS")
DoCmd.CopyObject , ReportName , acReport, "rpt_beoordelen"
DoCmd.OpenReport ReportName , acViewPreview, , "EmployeeNr='" & Me.empnr & "' and year=" & Me.Year
DoCmd.OutputTo acOutputReport, "", acFormatPDF, , True
DoCmd.Close acReport, ReportName
This generates and displays the report with the correct values. It asks for save location. And, once given, tries to save the file to given location. It quickly flashes a printing PDF to give location window.
After this the program stops. No file can be found at the given location and the report is still opened. Debugging the application shows me that
DoCmd.Close acReport, ReportName
is never reached. I do not get a errormessage and i have no clue what is going wrong. Could anyone give me a solution to this problem?
If you are having trouble getting DoCmd.OutputTo to work with the "active object" by leaving ObjectName empty (ref: here) then you could try this:
Open the "rpt_beoordelen" report and save its Record Source query as a saved Query named "rpt_beoordelen_base_data". Create a "rpt_beoordelen_data" saved Query with some generic SQL like...
SELECT * FROM rpt_beoordelen_base_data
...then make "rpt_beoordelen_data" the Record Source for the [rpt_beoordelen] report.
Now change the code from your question to something like this:
ReportName = "Appraisal_" & Trim(Str(Year)) & "_" & Me.empnr & "_" & Veilig(Me.empnr) & "_" & Format(Now(), "YYYY_MM_DD_HH_MM_SS")
DoCmd.CopyObject , ReportName , acReport, "rpt_beoordelen"
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.QueryDefs("rpt_beoordelen_data")
qdf.SQL = "SELECT * FROM rpt_beoordelen_base_data WHERE EmployeeNr='" & Me.empnr & "' and year=" & Me.Year
Set qdf = Nothing
DoCmd.OutputTo acOutputReport, ReportName, acFormatPDF
That will change your invocation of DoCmd.OutputTo to one that does not depend on the "active object" and may yield the results you desire. (FWIW, it's the only way I've gotten this method to work for generating PDF versions of reports.)
I'm trying to use a late binding to email from VBA in Access 2010 and Access 2003. 2003 gives me 'Could not complete the operation. Once or more paramet values are not valid.' and 2010 gives me 'Invalid procedure call or argument.' I've done the step through and it fails at .send near the bottom. Am I setting up my binding wrong? I'm trying to do this without using Microsoft Object Library in the References.
Thanks.
'Refers to Outlook's Application object
Dim appOutlook As Object
'Refers to an Outlook email message
Dim appOutlookMsg As Object
'Refers to an Outlook email recipient
Dim appOutlookRec As Object
'Create an Outlook session in the background
Set appOutlook = CreateObject("Outlook.Application")
'Create a new empty email message
Set appOutlookMsg = appOutlook.CreateItem(olMailItem)
'Using the new, empty message...
With appOutlookMsg
strSQL = "SELECT Email FROM Employees WHERE " & sqlVar & " = True"
Set myR = CurrentDb.OpenRecordset(strSQL)
Do While Not myR.EOF
Set appOutlookRec = .Recipients.Add(myR!Email)
appOutlookRec.Type = olTo
myR.MoveNext
Loop
strSQL = "SELECT Email FROM Employees WHERE '" & user & "' = Username"
Set myR = CurrentDb.OpenRecordset(strSQL)
Set appOutlookRec = .Recipients.Add(myR!Email)
appOutlookRec.Type = olCC
.Subject = wonum
.Body = "Department: " & strDep & vbNewLine & vbNewLine & _
"Issue is at: " & strIssue & vbNewLine & vbNewLine & _
"Priority is: " & strPriority & vbNewLine & vbNewLine & _
"Complete by: " & strDate & vbNewLine & vbNewLine & _
"Description: " & strDesc
.Send
End With
Without a reference, VBA will not know about Outlook constants such as olTo and olCC. With late binding (no reference), you must supply the values for constants rather than the names of the constants.
However, since you didn't report a compile error about those constants, that suggests your code module does not include Option Explicit in its Declarations section. Trying to troubleshoot VBA code without Option Explicit is a waste of time.
Add Option Explicit, then choose Debug->Compile from the VB Editor's main menu and fix anything the compiler complains about. Resume you troubleshooting afterward.
There is an article here on sending email via Outlook using early and late binding. In the "Late Bound Conversion Checklist" at the end, the last suggestion is
Add optional arguments that have a default value
I cannot vouch for that advice because when I need to send email messages from Access I use CDO, not Outlook. Still, it sounds like it might be worth a try.