I am parsing a worksheet into Access using the following code:
Sub LoadRates(ByRef TimesheetFile As Excel.Workbook)
On Error GoTo LoadDataCollection_Error
Dim i As Integer
Dim LastRow As Integer
Dim shRates As Excel.Worksheet
Set shRates = TimesheetFile.Worksheets("Rates")
shRates.ShowAllData
LastRow = shRates.Cells(shRates.Rows.Count, 1).End(xlUp).Row
shRates.Cells(1, 4).value = "Current"
Dim db As DAO.Database
Set db = CurrentDb
Dim strSQL As String
Dim dbWb As String
dbWb = "[Excel 12.0;HDR=YES;IMEX=1;Database=" & TimesheetFile.FullName & "].[Rates$A1:i" & LastRow & "]"
strSQL = "SELECT A.[Entity no] AS Entity,Staff AS Name, A.Current as Rates, Company, [2015 BCTC category] AS BCTC_Category,[2015 Rating] As Rating " & _
" INTO fromTimesheet " & _
" FROM " & dbWb & " AS A "
db.Execute strSQL, dbFailOnError
Exit Sub
LoadDataCollection_Error:
... do stuff...
End Sub
my problem is that I have to change the column 4's header to "Current" manually because the title is currently a date value, thus inappropriate for SQL to pick up
shRates.Cells(1, 4).value = "Current"
when I execute this code. sometimes it returns an error message saying it cannot find the field A.Current , and other times it would be able to find it. Is this caused by the workbook being set to Shared?
Any help would be appreciated.
Upon testing, I found out that this error has to do with the excel workbook being "Shared". Once I made the workbook exclusive, the code was able to pick up me editing the row value.
This leads me to believe that when I instantiate an excel workbook object that is being shared. It should be treated as read-only.
Hopefully this is helpful for others.
Yes, your column header is not being effectively saved and connection is using last saved instance.
Consider manually saving it after you make your change. Also, be sure you have write access to save workbook and not in shared/read-only (or alternatively save a different temp workbook for import):
shRates.Cells(1, 4).value = "Current"
TimesheetFile.Save
But also consider using DoCmd.TransferSpreadshet method instead of worksheet connection (which can facilitate "shared" process). Usually one uses a true database for connection and not flatfiles like spreadsheets.
Sub LoadRates(ByRef TimesheetFile As Excel.Workbook)
On Error GoTo LoadDataCollection_Error
Dim i As Integer, LastRow As Integer
Dim shRates As Excel.Worksheet
Set shRates = TimesheetFile.Worksheets("Rates")
shRates.ShowAllData
LastRow = shRates.Cells(shRates.Rows.Count, 1).End(xlUp).Row
shRates.Cells(1, 4).value = "Current"
TimesheetFile.Close True ' SAVES AND CLOSES
DoCmd.TransferSpreadsheet acImport, "fromTimesheet", _
TimesheetFile.FullName, True, "Rates!"
Exit Sub
LoadDataCollection_Error:
... do stuff...
End Sub
Related
I am working on an export code to copy and export the current record I am viewing to an excel spreadsheet. Below is my code
Private Sub cmdExportFilename_Click()
Dim sFilename As String
Dim StrSQL As String
StrSQL = "Select * FROM [MainData] WHERE ([ID]=" & Me![ID] & ");"
sFilename = "C:\Desktop\exportResults.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, StrSQL,
sFilename, True
End Sub
When I run this I get a Run-time error '3011' saying it could not find the object (though it pulls my Select string and correctly identifies I'm viewing record 86 with the error message" and says the object doesn't exist.
My previous code successfully exported data but it outputted the entire query results instead of just the viewed record.
Private Sub cmdExportFilename_Click()
Dim sFilename As String
sFilename = "C:\Users\cpastore\Desktop\exportResults.xlsx"
DoCmd.OutputTo acOutputForm, "OpenComplaintsQuery", acFormatXLSX, sFilename,
AutoStart:=True
End Sub
With Outputto command I do not see where I can select certain things in Parameters. So I thought I would try TransferSpreadsheet command instead.
My end goal ultimately is with the record I am viewing, when I click the button, it exports 6 or 7 fields of 25 that the form displays to an excel spreadsheet where those values Goto a very specific cell location in the sheet. I know with codes above I am a long way from there but I am slowly learning.
Edit: Adding new Code per June7 post suggestion. Ran into another Runtime Error
Private Sub cmdExportfield_Click()
Dim rsGroup As DAO.Recordset
Dim QIMS As String
Dim path As String
path = "C:\Desktop\"
Set rsGroup = CurrentDb.OpenRecordset("SELECT
OpenComplaintsQuery.QIMS# " & "FROM OpenComplaintsQuery GROUP
BY OpenComplaintsQuery.QIMS#", dbOpenDynaset)
Do While Not rsGroup.EOF
QIMS = rsGroup!QIMS#
Dim rsExportSQL As String
rsExportSQL = "Select * FROM OpenComplaintsQuery" & "WHERE
(((OpenComplaintsQuery.QIMS#='" & QIMS & "'))"
Dim rsExport As DAO.QueryDef
Set rsExport = CurrentDb.CreateQueryDef("myexportquerydef",
rsExportSQL)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9,
"myexportquerydef", path & "exporttest.xlsx", True
CurrentDb.QueryDefs.Delete rsExport.Name
rsGroup.MoveNext
Loop
End Sub
I am working in MS Access. All the tables and views are linked to a SQL Server database. I want to write a procedure that will retrieve and store all of the formatting information about these objects. A lot of this information is available from the property sheet (I open a table in Design View, and hit F4 for the property sheet). Eg:
Filter
Order By
Filter On Load
Order by On Load
Order by On
How do I retrieve these properties programmatically? I only see them listed for Reports.
Note that I need to retrieve the values, not just set them. I know about the SetFilter method, and that's not what I need.
The linked table exists as a DAO.TableDef in your database's TableDefs collection. So you can check the TableDef.Properties collection for those 5 properties.
However beware that both Filter and OrderBy are user-created instead of default properties, which means they are not included in the Properties collection unless you've assigned them values. Attempting to retrieve one which doesn't exist triggers error 3270, "Property not found". You can trap that error, respond to it as you wish, and continue on for the other properties you're interested in. Or you could first determine whether the property exists and only attempt to retrieve its value when it does exist.
This code sample uses the first approach (trap the error):
Const cstrTable As String = "YourLinkedTableNameHere"
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strMsg As String
Dim varProp As Variant
Dim varProperties As Variant
On Error GoTo ErrorHandler
varProperties = Array("Filter", "FilterOnLoad", "OrderBy", _
"OrderByOn", "OrderByOnLoad")
Set db = CurrentDb
Set tdf = db.TableDefs(cstrTable)
For Each varProp In varProperties
Debug.Print varProp, tdf.Properties(varProp).Value
Next
ExitHere:
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 3270 ' Property not found.
strMsg = "Property '" & varProp & "' not found."
'MsgBox strMsg
Debug.Print strMsg
Resume Next
Case Else
strMsg = "Error " & Err.Number & " (" & Err.Description & ")"
MsgBox strMsg
Resume ExitHere
End Select
How about something like this? (I've defined "table2" to have two fields, "PropertyName" and "PropertyValue"..."table1" is a placeholder for any of your existing tables)
Dim i As Integer
Dim j As Integer
Dim RS As DAO.Recordset
On Error Resume Next
Set RS = CurrentDb.OpenRecordset("select * from table2")
j = CurrentDb.TableDefs("table1").Properties.Count
For i = 0 To j - 1
RS.AddNew
RS!PropertyName = CurrentDb.TableDefs("table1").Properties(i).Name
RS!PropertyValue = Nz(CurrentDb.TableDefs("table1").Properties(i).Value, "-")
RS.Update
Next i
Every month I have to UPDATE my MS Access db from approximately 30 excel files. They have all the same structure and format. I try to modify this code several times to update each tables in my db in once but i didn't succeed. (found in this forum)
I have 3 questions:
How is it possible to say to the vba code to look at this range in the excel template which correspond to this column in the MS Access db?
How can i make this vba code update all the tables in once based on the Primary Key?
Then, Is it possible to select the Folder where all these excel files are and the code will loop through all files?
Public Sub UpdatePriceList()
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim sProduct As String, sVariety As String, cPrice As Variant
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=C:\Users\Gord\Desktop\Database1.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "PriceList", cn, adOpenKeyset, adLockOptimistic, adCmdTable
Range("A2").Activate ' row 1 contains column headings
Do While Not IsEmpty(ActiveCell)
sProduct = ActiveCell.Value
sVariety = ActiveCell.Offset(0, 1).Value
cPrice = ActiveCell.Offset(0, 2).Value
rs.Filter = "product='" & sProduct & "' AND variety='" & sVariety & "'"
If rs.EOF Then
Debug.Print "No existing record - adding new..."
rs.Filter = ""
rs.AddNew
rs("product").Value = sProduct
rs("variety").Value = sVariety
Else
Debug.Print "Existing record found..."
End If
rs("price").Value = cPrice
rs.Update
Debug.Print "...record update complete."
ActiveCell.Offset(1, 0).Activate ' next cell down
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
thank you in advance!
If you know how to deal with a single excel file and convert it to acess table and all the rest of file will be treated the same way. You can use a bot which will automate the task and do it quickfast. You just have to give it the "instruction" how to deal with single file and it will do the rest.
The instruction can be as simple as a notepad file with table containing the mouse positions and the stroken keyboards key necessary to deal with one file.
You may use "Autoit V3 script"
I have code written to pull a specific file from a folder, insert it into an attachment field (local_attachment) and which creates a new record in table TEMP_attachment. I am trying to pull all the files from a folder and have them each be a new record in the table but I keep running into issues where I either pull all the files and they all go into one record, or it won't pull any. Thank you for your help!!!
Here is my code:
Dim x As Long
Dim strFile As String
Dim db As DAO.Database
Dim rs As DAO.Recordset2
Dim rsA As DAO.Recordset2
Dim fld As DAO.Field2
Dim SQL As String
x = 1
strFile = "C:\dev\test_file2.txt"
SQL = "INSERT INTO TEMP_Attachment (ID) "
SQL = SQL & "VALUES (" & x & ")"
DoCmd.RunSQL SQL
Set db = CurrentDb
Set rs = db.OpenRecordset("TEMP_Attachment")
Set fld = rs("local_attachemnt")
'Navigate through the table
Set rsA = fld.Value
rs.Edit
rsA.AddNew
rsA("FileData").LoadFromFile strFile
rsA.Update
rs.Update
The problems with your code can be fixed my taking a more methodical approach. As I see it, you need to find all the files in the folder, add a record for each one, add an attachment record for the file, read the file data into the new record, and generate a unique key for the parent record.
Rather than try to do everything at once, let's break into pieces and take them in reverse order, so we're dealing with the smallest problems first:
First, let's figure out how we are going to generate a key. The easiest way to do this is to use an Autonumber field. Rather than cook up something fancier, I'm going to assume this is the solution you will use. This will make DoCmd.RunSQL unnecessary and simplify the whole operation.
Second, write a routine which adds one file to one record in the database, and make sure this is working. My suggestion would be to create parameters for a recordset to the main table and a path to the file, like so (I have not tested this, that will be your job. I've added error handlers to help you work out any issues):
Private Sub AddFileAttachment(ByRef rs As DAO.Recordset, ByVal sPath As String)
Dim rsAttachments As DAO.Recordset
On Error Goto EH
With rs
'(this will generate a new Autonumber in the main table)
.AddNew
'this will create a new attachment in the field and add it
Set rsAttachments = .Fields("local_attachemnt").Value
With rsAttachments
.AddNew
.Fields("FileData").LoadFromFile sPath
.Update
.Close
End With
'this is what adds the main record
.Update
End With
EH:
With Err
MsgBox .Number & vbcrlf & .Source & vbCrLf & .Description
End With
FINISH:
If Not rs Is Nothing Then
rs.Close
Set rs = Nothing
End If
If Not rsAttachments Is Nothing Then
rsAttachments.Close
Set rsAttachments = Nothing
End If
End Sub
And call it like so:
Private Sub cmdTest_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
On Error Goto EH
Set db = CurrentDb
Set rs = db.OpenRecordset("TEMP_Attachment")
AddFileAttachment rs, "C:\dev\test_file2.txt"
Goto FINISH
EH:
With Err
MsgBox .Number & vbcrlf & .Source & vbCrLf & .Description
End With
FINISH:
rs.Close
End Sub
Important! Perfect the first routine before moving on. You should test it until you know it works over and over. You should be able to click the button it is attached to 10 times and each time get a new record with the file attached.
Once you know this is working, you are ready to write the main routine that calls it for each file you are attaching. I will not include that here, but would suggest researching the FileSystemObject. You should be able to find a lot of vba examples for how to get all the files in a folder. You would loop through them and call your routine for each file the same way it is called in the test above, passing in the open recordset.
I have an application in Access 2007 that is creating a workbook with N sheets i created a macro to be inserted into this workbook which works perfectly fine. But the next step is to add a Shortcut Key to the Marco so far i've seen to methods online to assist. The First attempt gives no errors but does not assign the shortcut key either
1)
Excel_App.OnKey "^{h}", "Sheet1.HideChange"
2)Excel_App.MacroOptions Macro:="Sheet1.HideChange", Description:="Hide Columns in Line Level", hasshortcutkey:=True, ShortcutKey:="h"
My variables assigned to my method
Dim Excel_App As Excel.Application
Dim wkb As Excel.Workbook
Dim wks, wks2, wks3, wks4, wks5, wks6, wks7, wks8 As Excel.Worksheet
Dim i As Integer
Dim xlmodule As Object 'VBComponent
Dim coaches As Recordset
Set Excel_App = New Excel.Application
Excel_App.Visible = False
Set wkb = Excel.Workbooks.Add
Below is where i last placed the shortcut, i've attempted to move the line of code before and after saving however i still get 1004 err.
With wkb
ActiveSheet.Move Before:=Worksheets(1)
.Title = "CHANGE REQUEST"
.Subject = "CHANGE REQUEST"
' Add a macro to the module...
Dim strCode As String
strCode = _
"Sub HideChange()" & vbCr & _
" Columns(""A:A"").Select Selection.EntireColumn.Hidden = True " & vbCr & _
"end sub"
Dim module As VBComponent
Set module = wkb.VBProject.VBComponents(2)
module.CodeModule.AddFromString strCode
Excel_App.MacroOptions Macro:="Sheet1.HideChange", Description:="Hide Columns in Line Level", hasshortcutkey:=True, ShortcutKey:="h"
.SaveAs FileName:=strDir & "\CHANGE REQUEST FORM.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
.Close
End With
Excel_App.Quit
Can anyone help me figure out how this works ?
if you need more details to my question please ask, Thank you for your time!
Try removing "Sheet1" from "Sheet1.HideChanges", it is not required (or correct).
MacroOptions :MSDN
OnKey :MSDN