Run-time error '3061'. Too few parameters. Expected 1 Access 2013 - ms-access

I use this line of code:
Call SendTQ2XLWbSheetData("qryCustExportStyColOnlyDrop", "Data", "C:\Users\" & GetLogonName() & "\FWD Order Customer Export.xlsm")
To call and pass parameters to this Function:
Public Function SendTQ2XLWbSheetData(strTQName As String, strSheetName As String, strFilePath As String)
' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to send it to
' strFilePath is the name and path of the file you want to send this data into.
Dim rst As DAO.Recordset
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim fld As DAO.Field
Dim strPath As String
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
On Error GoTo err_handler
strPath = strFilePath
Set rst = CurrentDb.OpenRecordset(strTQName)
Set ApXL = CreateObject("Excel.Application")
Set xlWBk = ApXL.Workbooks.Open(strPath)
ApXL.Visible = True
Set xlWSh = xlWBk.Worksheets(strSheetName)
xlWSh.Visible = True
xlWSh.Activate
'clear any current size ranges
ApXL.Range("DataRange").Select
ApXL.Selection.ClearContents
xlWSh.Range("A1").Select
For Each fld In rst.Fields
ApXL.ActiveCell = fld.Name
ApXL.ActiveCell.Offset(0, 1).Select
Next
rst.MoveFirst
xlWSh.Range("A2").CopyFromRecordset rst
xlWSh.Visible = False
rst.Close
Set rst = Nothing
xlWBk.Close True
Set xlWBk = Nothing
ApXL.Quit
Set ApXL = Nothing
Exit_SendTQ2XLWbSheet:
Exit Function
err_handler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
Resume Exit_SendTQ2XLWbSheet
End Function
However, when I run it I keep receiving error 3061 Too Few Parameters - Expected 1. When I step through, it is this line of code causing the error:
Set rst = CurrentDb.OpenRecordset(strTQName)
However if I hover over the above line in debug, it is showing the name of the query (qryCustExportStyColOnlyDrop) I am passing.
What am I missing?
Thanks.

Most likely you have in your query a reference to a form control.
The value from this you must pass as a parameter if you run the query from code.
So, create a QueryDef object in your function, pass the parameter, and open your recordset from the QueryDef object.

Related

Save Excel Workbook From Access VBA

I am exporting a recordset from an access query to an Excel Workbook. The export goes fine, and my syntax prompts the user for a filename/location just as I need. However, the file is not actually saved. Am I missing a step in the process or what code changes need to take place in order to have this function?
Sub ETE()
Dim ExcelApp As Object, wbOutput As Object, wsOutput As Object, bExcelOpened As Boolean
Dim db As DAO.Database, rs As DAO.Recordset, targetRow As Long
Dim targetPath As String, fd As FileDialog, Title As String, saveInfo As Variant
DoCmd.Hourglass True
Set ExcelApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Err.Clear
On Error GoTo Error_Handler
Set ExcelApp = CreateObject("Excel.Application")
bExcelOpened = False
Else
bExcelOpened = True
End If
On Error GoTo Error_Handler
ExcelApp.ScreenUpdating = False
ExcelApp.Visible = False
Set wbOutput = ExcelApp.Workbooks.Add()
Set wsOutput = wbOutput.Sheets(1)
Set db = CurrentDb
Set rs = db.OpenRecordset("qryTakeDataToExcel", dbOpenSnapshot)
With rs
If .RecordCount <> 0 Then
'Write the data to Excel
End If
End With
Set fd = Application.FileDialog(msoFileDialogSaveAs)
With fd
.AllowMultiSelect = False
.Title = "Select Save Location And File Name"
.InitialFileName = "File_" & Format(Now(), "mmddyyyy") & ".xlsx"
If .Show = True Then
wbOutput.SaveAs FileName:=fd.InitialFileName, FileFormat:=50
wbOutput.Close
End If
End With
End Sub
Your filedialog code is not working as expected, and because of that, you're not getting a valid file name and location.
If you want to return the file name picked, you should use .SelectedItems(1), not .InitialFileName. .InitialFileName sets an initial value and doesn't return the full path.
If .Show = True Then
wbOutput.SaveAs FileName:=.SelectedItems(1), FileFormat:=50
wbOutput.Close
End If
This would've probably been easier to catch if you'd have used a valid error handler. Use On Error GoTo 0 to use the default error handler.

Adding parameter to existing code to export an Access Query to Excel

'Below is the current code that I have and it will export to the excel workbook and worksheet correctly. The only problem is that I need to limit the data that gets exported by a month end date range (example: 1/31/2017 to 4/30/2017) and also by a plant number (example: "4101")
thanks for any help it is greatly appreciated.
Public Function InventoryXport_4100()
Dim appXL As Object
Dim wb As Object
Dim wks As Object
Dim xlf As String
Dim rs As DAO.Recordset
Dim fld As Field
Dim intColCount As Integer
xlf = "Z:\COST ACCOUNTING INFO\Inventory Reports\MyFile.xlsx"
Set rs = CurrentDb.OpenRecordset("(QS)_Inventory")
Set appXL = CreateObject("Excel.Application")
Set wb = appXL.Workbooks.Open(xlf)
Set wks = wb.Sheets("Inventory Xport") 'Sheet name
If rs.EOF = True Then
MsgBox "No data", vbOKOnly
Exit Function
End If
With appXL
.Application.worksheets("Inventory Xport").SELECT
.Application.columns("A:AQ").SELECT
.Application.columns.Clear
End With
intColCount = 1
For Each fld In rs.Fields
wks.Cells(1, intColCount).Value = fld.Name
intColCount = intColCount + 1
Next fld
appXL.displayalerts = False
wks.Range("A2").CopyFromRecordset rs
appXL.Visible = True
With appXL
.Application.worksheets("Inventory Xport").SELECT
.Application.columns("A:AQ").SELECT
.Application.columns.AutoFit
.Application.Range("A2").SELECT
.Application.ActiveWindow.FreezePanes = True
End With
wb.Save
wb.Close
appXL.Quit
Set wb = Nothing
rs.Close
Set rs = Nothing
End Function
You need to put the filter conditions into a where clause on your query:
Set rs = CurrentDb.OpenRecordset("SELECT * FROM [(QS)_Inventory] WHERE ...")
If you need help with the syntax of the where clause you will need to post the structure of your query (i.e. at least give the names and data types of the columns that you want to filter on). Also, if you want to pass these parameters into the function then you'll need to include them in the Function declaration with suitable parameter names, and replacing each ???? with the appropriate data type:
Public Function InventoryXport_4100(prm1 As ????, prm2 As ????, prm3 As ????)
By the way, why is this a Function rather than a Proc - there's no return value or even return data type set?
Edit following comments back and forth:
So try something like
Set rs = CurrentDb.OpenRecordset("SELECT * FROM [(QS)_Inventory] " & _
"WHERE [Plant] = '4101' " & _
"AND [Per] Between #01/31/2017# And #04/30/2017#")

Passing Functions through Sub Procedure

I am trying to call a function when running a sub proecudere, however, I keep getting an error message saying "Argument not optional", can someone help?
Code as follows:
Public Sub ret()
Dim FSO As New Scripting.FileSystemObject
Const cstrFolderF = "\\tblSCFLAGCHECKER.txt"
If FSO.FileExists(cstrFolderF) Then
DoCmd.RunSQL "DELETE * FROM [tblSCFLAG_CHECKER]"
DoCmd.TransferText acImportDelim, "tblSCFLAG_CHECKER", "tblSCFLAG_CHECKER", cstrFolderF, True
changefieldnames
Else
'SCAnswer = MsgBox("SC Flags does not exist, do you wish to continue?", vbYesNo Or vbQuestion Or vbDefaultButton2)
'If SCAnswer = vbNo Then Exit Sub
End If
End Sub
Private Sub changefieldnames()
Dim db As Database
Dim tdf As TableDef
Dim n As Object
Set db = CurrentDb
Set tdf = db.TableDefs("tblSCFLAG_CHECKER")
For Each n In tdf.Fields
If n.Name = "?Person ID" Then n.Name = "Person ID"
Next n
Set tdf = Nothing
Set db = Nothing
End Sub
Your changefieldnames function requires two arguments but you give none in the call after
DoCmd.TransferText acImportDelim, "tblSCFLAG_CHECKER", "tblSCFLAG_CHECKER", cstrFolderF, True
changefieldnames
As a remark: you should try to debug your code instead of just posting an error without even stating where exactly the error occurs.

Adding DBfailonerror in access vb creates compile error invalid use of property

An import sub that has been created in access works OK but when DBfailonerror is added a compile error invalid use of property is encountered when the sub is run from the vb editor.
Any advice re: this would be most appreciated. Code is as follows:
Sub Importcl()
'DATA DECLARATIONS
Dim fso As New FileSystemObject
Dim t As TextStream
Dim strFilePath As String
Dim Cnr As String
Dim Cnri As String
Dim Cnrii As String
Dim Cnriii As String
Dim Sqlstr As String
Dim Db As DAO.Database
'SET COUNTERS TO ZERO
Cnr = 0
Cnri = 0
Cnrii = 0
Cnriii = 0
'Point to DB
Set Db = CurrentDb()
'SET TXT FILE PATH
strFilePath = "C:\Users\Vlad\CSV import\EV WORK\Book1.txt"
'ERROR HANLDER FOR TXT FILE PATH AND COUNTING OF TXT FILE LINE ITEMS
If fso.FileExists(strFilePath) Then
Set t = fso.OpenTextFile(strFilePath, ForReading, False)
Do While t.AtEndOfStream <> True
t.SkipLine
Cnr = Cnr + 1
Loop
t.Close
Else: MsgBox ("Txt File not Found - Check File Path")
Exit Sub
End If
'DISPLAY LINE RECORDS COUNTED IN TXT FILE TO BE ADDED TO TABLE
Debug.Print Cntr; " Incl header"
MsgBox (Cnr - 1 & " records to be added")
'COUNT & DISPLAY CURRENT RECORD COUNT IN TARGET TABLE
Cnri = DCount("[Case Date]", "All Caseload Data New")
If MsgBox(Cnri & " -Current Records in table- All Caseload Data New - Continue
with Import?", vbYesNo, "Import") = vbYes Then
Db.Execute _
"INSERT INTO [All Caseload Data New] SELECT * FROM[Text;FMT=Delimited;HDR=Yes;
DATABASE=C:\Users\Dev\CSV import\DEV WORK\].[Book1#txt];"
dbFailOnError
Db.TableDefs.Refresh
Else: Exit Sub
End If
Cnrii = DCount("[Case Date]", "All Caseload Data New")
Cnriii = Cnrii - Cnri
MsgBox (Cnriii & " New records added to table All Caseload Data New")
End Sub
With this code to start ...
Dim db As DAO.database
Dim strInsert As String
strInsert = "INSERT INTO tblFoo (some_text) VALUES ('bar');"
Set db = CurrentDb
Then these 2 Execute statements ..
db.Execute strInsert
dbFailOnError ' triggers error
db.Execute strInsert, dbFailOnError ' compiles without error
Include dbFailOnError on the same line as Execute. Placing dbFailOnError on a separate line triggers that "invalid use of property" compile error.

Access 2010 VBA to put one field from a query in a variable

In Access 2010 I need to be able to click a command button that will run a query that returns a small two field recordset. Then put the second field in that recordset into a string variable.
This string variable is a link to a word document on the network. the second part of the code will then open the word document.
Any help is GREATLY appreciated.
I am getting the Error: "Object variable or With block variable not set"
My Code looks like this:
`Option Compare Database
Private Sub cmdCESpec_Click()
On Error GoTo Err_cmdCESpec_Click
Dim db As Database
Dim rs As DAO.Recordset
Dim s As String
Dim specSheet As String
s = "SELECT p.PartNum, p.CE_SpecSheet FROM tblParts p WHERE p.PartNum = '" & [Forms]![frmSpecSheet]![cboPartNum] & "'" 'Chooses the correct Spec Sheet.
Set rs = db.OpenRecordset(s)
specSheet = rs.Fields("CE_SpecSheet") 'Chooses the Spec Sheet Field
rs.Close
Dim oApp As Object
Set oApp = CreateObject("Word.Application")
oApp.Visible = True
With oApp
.Documents.Open (specSheet)
End With
Exit_cmdCESpec_Click:
Exit Sub
Err_cmdCESpec_Click:
MsgBox Err.Description
Resume Exit_cmdCESpec_Click
End Sub
After dissecting your code.. this:
"..WHERE (((tblParts.PartNum)=[Forms]![frmSpecSheet]![cboPartNum]));"
embeds the words Forms!etc into your sql-statement, it doesn't insert the combo-box value into the statement.
You need to take the form reference out of the string:
Dim db As Database
Dim rs As Recordset
Dim s As String
Dim specSheet As String
s = "SELECT tblParts.PartNum, tblParts.CE_SpecSheet FROM tblParts WHERE " _
& "tblParts.PartNum=" & [Forms]![frmSpecSheet]![cboPartNum]
'Chooses the Correct Spec Sheet
Set db = CurrentDb
Set rs = db.OpenRecordset(s)
specSheet = rs.Fields("CE_SpecSheet")
'Chooses the Spec Sheet Field
rs.Close
Dim oApp As Object
Set oApp = CreateObject("Word.Application")
oApp.Visible = True
With oApp
.Documents.Open ("specSheet")
End With
If the combobox's value is text then you'll need to also surround this with apostrophes.
You also don't need to SELECT the field tblParts.PartNum, you can just refer to it in the WHERE clause.
You haven't posted much information but what I gather you're looking for is Recordset
Dim db As Database
Dim rs As Recordset
Dim s As String
Dim myString As String
s = "SELECT * FROM myTable1;" 'Replace with the SQL you need
Set db = CurrentDb
Set rs = db.OpenRecordset(s)
myString = rs.Fields("myFieldName1") 'Replace myFieldName with the appropriate field name
rs.Close