MS Access VBA - Run Multiple Saved Imports on double click - ms-access

I'm trying to save myself some time as I update a few similar databases with new data every morning using saved imports. I currently have the following double-click code on a logo which checks to see if I'm the current user of the database (because I'm the only one who will be updating) and if I am the current user, run two saved imports:
Private Sub Image480_DblClick(Cancel As Integer)
Dim sHostName As String
' Get Host Name / Get Computer Name
sHostName = Environ$("computername")
If sHostName = "GS100ZEC" Then
DoCmd.RunSavedImportExport "Import-DocCreator CPD"
DoCmd.RunSavedImportExport "Import-DocCreator CD"
End If
End Sub
The problem seems to be that it is only updating one of these tables with the new data, the second table stays the same. Any tips or something I may have missed would be appreciated!
Update:
Buddy of mine helped me formulate a loop for this function and still same problem, the second import is not running! Code as follows:
Private Sub Image480_DblClick(Cancel As Integer)
Dim sHostName As String
Dim i As Integer
Dim docs(1 To 2) As String
' Get Host Name / Get Computer Name
sHostName = Environ$("USERPROFILE")
docs(1) = "Import-DocCreator CPD"
docs(2) = "Import-DocCreator CD"
If sHostName = "C:\Users\z003nttv" Then
For i = 1 To 2
DoCmd.RunSavedImportExport docs(i)
Next i
End If
End Sub
Also tried to delete the saved import itself and recreating it, still didn't import.

Related

tableadapter not deleting programatically removed datatable rows

I have a dataset linked with a MYSQL database via tableadpators and a TableAdpaterManager (all autographed through designer view). The visual studio route was setting up a DataSource and then dragging individual tables onto the form.
Now, I can update, insert and delete records in the database if I edit the datagridviews manually. However, if I remove datarows programatically, the rows are not deleted in the database.
The removal code:
Public Shared Sub RemoveDuplicateRowsViaField(dt As DataTable, RowName As String)
Dim rowList As New List(Of String)
Dim dr As DataRow
For i = dt.Rows.Count - 1 To 0 Step -1
dr = dt(i)
If rowList.Contains(dr.Item(RowName)) Then
dt.Rows.Remove(dr)
Else
rowList.Add(dr.Item(RowName))
End If
Next
dt.DataSet.AcceptChanges()
End Sub
And the 'save' code:
Private Sub SaveOrganisationsBT_Click(sender As Object, e As EventArgs) Handles SaveOrganisationsBT.Click
Me.Validate()
Me.Gi_usersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.dbDS)
End Sub
I've tried many things including looking into the tableAdapters in dataset design view, but am at a loss. Can anyone help?
Nevermind. Solved it. It appears to be around the use of AcceptChanges on the datasource. The code below works. I've read that datarow.remove both deletes the row and accepts changes. I'm guessing if changes are accepted then the tableadapter can't discern it needs deleting from its non 'dirty' state, given changes have been accepted, thus clearing the status of the row? Just supposition. The working code:
Public Shared Sub RemoveDuplicateRowsViaField(dt As DataTable, RowName As String)
Dim rowList As New List(Of String)
Dim dr As DataRow
For i = dt.Rows.Count - 1 To 0 Step -1
dr = dt(i)
If rowList.Contains(dr.Item(RowName)) Then
dr.Delete()
Else
rowList.Add(dr.Item(RowName))
End If
Next
End Sub

DIsplay real time SQL data on web form

I am working on a small project but currently stuck in the process and your help would be much appreciated.
I am trying to display data from one of my SQL tables onto web form (asp), which will effectively be updating as long as data is being entered into the table.
I have managed to get it to work by using the META Tag which refreshes the page every 2 seconds, but I know this is not an ideal way of doing it. It was advised to me to update the web form only from server to client when there is a new inserted value, however I do not know how to approach this.
Please see below to my current code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = "Cache Refresh:" & _
Date.Now.ToLongTimeString
SqlDependency.Start(GetConnectionSTring())
Using connection As New SqlConnection(GetConnectionSTring())
Using Command As New SqlCommand(GetSQL(), connection)
Dim Dependency As New SqlCacheDependency(Command)
Dim NumberOfMinutes As Integer = 3
Dim Expires As Date = _
DateTime.Now.AddMinutes(NumberOfMinutes)
Response.Cache.SetExpires(Expires)
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(True)
Response.AddCacheDependency(Dependency)
connection.Open()
GridView1.DataSource = Command.ExecuteReader()
GridView1.DataBind()
End Using
End Using
End Sub
Private Function GetConnectionSTring() As String
Return "Data Source=xxxxxxxxx; Initial Catalog=Test; User ID=xxx; Password= xxx;"
End Function
Private Function GetSQL() As String
Return "SELECT ProductCode, ProductName, Cost FROM dbo.OrderTempTable"
End Function
Thank you for your input.
I think you have to check the DB every certain time.
THIS is for PHP but the idea is the same.
HERE another example.

Access 2013 Dlookup issue

good morning all
I usually find the answer to my queries already on here but this one has me stumped. I have 3 tables,
area containing Area and Region, Phones comtaining phone number and IMSI (SIM number) and a log containing all 4 fields.
I've put in a Dlookup (as found on this site) on the log and although it works the first time the event is triggered it allways comes up with the wrong value. It's probably something stupid and simple, it's years since I used Access and that was probably Access 2007 or something.
Hope you can help. I have created a cut down test version but not sure how to add it to the question.
The VB code is here
Private Sub Area_Change()
Dim FoundRegion As String
FoundRegion = DLookup("[Region]", "[Area]", "'[Area]![Area]=[Area]'")
Me.Region = FoundRegion
End Sub
Private Sub Phone_Number_AfterUpdate()
Dim FoundIMSI As Double
FoundIMSI = DLookup("[IMSI ]", "[phones]", "'[phones]![Phone Number]=[Phone Number]'")
Me.IMSI = FoundIMSI
End Sub
not sure how to add the database
Private Sub Area_Change()
Dim FoundRegion As String
FoundRegion = DLookup("[Region]", "[Area]", "'[Area]![Area]=[Area]'")
Me.Region = FoundRegion
End Sub
Private Sub Phone_Number_AfterUpdate()
Dim FoundIMSI As Double
FoundIMSI = DLookup("[IMSI ]", "[phones]", "'[phones]![Phone Number]=[Phone Number]'")
Me.IMSI = FoundIMSI
End Sub

Why do some forms suddenly lose functionality?

once in a while in this application I have been working on a form will suddenly lose all of it's functionality with the database and I am forced to erase all of the work I have done on it and completely re-build it.
For instance adding a new entry to the database; I can hit Add New which calls bindingsource.addnew() enter all of the required information into the text boxes, hit save then when I close and re-open the form nothing is displayed in the datagrid. If I go directly to the table in the SQL Database nothing has been added here either?
It seems to escalate suddenly, when I edit an entry in a table then save it it does not update. After that I cannot add rows to it but it will let me delete rows and save that?
Tablename.bindingsource.addnew()
Tablename.bindingsource.endedit()
Tablename.tableadapter.update(datasetname.tablename)
This is what I have used for adding rows and saving new entries plus edits to the data source for some time now. Is there something I need to be watching out for otherwise?
Private Sub createnew()
'' CREATE AND SAVE NEW ENTRY
CalibratedEquipmentBindingSource.AddNew()
dateaddedlbl.Text = datelbl.Text
CalibratedEquipmentBindingSource.EndEdit()
Calibrated_EquipmentTableAdapter.Update(MacroQualityDataSet.Calibrated_Equipment)
End Sub
Private Sub savebtn_Click(sender As Object, e As EventArgs) Handles savebtn.Click
Try
Dim accountname As String = "macroqc"
Dim acocuntkey As String = My.Settings.Storagekey1
Dim creds As StorageCredentials = New StorageCredentials(accountname, acocuntkey)
Dim account As CloudStorageAccount = New CloudStorageAccount(creds, useHttps:=True)
Dim client = account.CreateCloudBlobClient()
Dim container As CloudBlobContainer = client.GetContainerReference(My.Settings.smallequipmentcertscontainername)
container.CreateIfNotExists()
Dim blob As CloudBlockBlob = container.GetBlockBlobReference(My.Settings.ticketsource)
Using FileStream = System.IO.File.OpenRead(My.Settings.ticketsource)
blob.UploadFromStream(FileStream)
filenamelbl.Text = My.Settings.ticketsource
'' GET HTTPS: PATH OF BLOB
''blob.Uri.AbsoluteUri & blob.Uri.AbsolutePath
End Using
Catch ex As Exception
MessageBox.Show("Sorry an error has occured while uploading your file: " & Environment.NewLine & ex.ToString, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
If datelbl.Text.Length > 3 Then
dateeditedlbl.Text = datelbl.Text
End If
CalibratedEquipmentBindingSource.EndEdit()
Calibrated_EquipmentTableAdapter.Update(MacroQualityDataSet.Calibrated_Equipment)
gridcolors()
MsgBox("Save Complete!")
End Sub
End Class

Exporting an array of custom objects into Access table

I have a timesheet system in excel with 3 rows (standard time, overtime, double time) for each of our (100+) employees, and one column for each cost code on the site. This ends up being a giant matrix, most of which is empty. My solution is to basically create an employee datatype which stores the employee information and hours for a single cost code.
Public Type Employee
Name As String
Trade(1 To 3) As String
EmpNum As Long
Comment As String
AddOns(1 To 3) As Single
Allowance(1 To 3) As Single
Contract As Long
CostCode As Long
STHours As Single
OTHours As Single
DTHours As Single
WorkDate As Date
End Type
I can process the spreadsheet and organize the information in excel as an array of employee-type objects, but I'm not familiar with how to export this into Access, and most questions relate to exporting from excel cells to Access. I can obviously put these objects into cells on another worksheet and do it that way, but it seems like there should be a better way.
Currently my best guess is something like this:
Insert data form Excel to Access 2010 using VBA
but then I'd be making 100+ updates to the table for each export.
Is there an efficient way to create a table object in VBA, populate it with the array information, and then append it to the end of my table in Access in a single update?
Thanks.
-Sean
The easiest way is to create a table link in Access. Table links look like tables in the rest of Access, but the data is stored externally. The data could be inside another Access database, or inside a SQL Server database, or what have you.
In particular, the data can be in an Excel spreadsheet. Define a table in Excel that contains the data in the format that's right for your Access application. Then build a table link in Access that links back to the table you defined in Excel.
When you update the Excel table, the updated results will automatically appear the next time you reference the table link in Access.
thanks for the help from everyone ... I just wanted to share what I came up with for a solution. I ended up building a function to insert one object into the database ... copied and modified from the interwebs. Code below, cheers!
Public Function InsertTimeRecord(EmpData As Employee) As Boolean
Dim SaveTime As Date
Dim db As DAO.Database
Dim rs As DAO.Recordset
'//Database Location
Const DB_LOCATION = "C:\access\KMP Tracker.mdb"
'//If errors occur the function will exit with a return value of false (insertion failed)
On Error GoTo ErrHandler:
'//Table has a datecreated/datemodified timestamp for each record
SaveTime = Now
'//Open Database
If db Is Nothing Then
Set db = DAO.Workspaces(0).OpenDatabase("C:\access\KMP Tracker.mdb") 'Removed DB_LOCATION
End If
'//Open Table
If rs Is Nothing Then
Set rs = db.OpenRecordset("Timesheet Data", dbOpenDynaset)
End If
'//Create a new record
With rs
.AddNew
![EmpName] = EmpData.Name
![Trade1] = EmpData.Trade(1)
![Trade2] = EmpData.Trade(2)
![Trade3] = EmpData.Trade(3)
![EmpNum] = EmpData.EmpNum
![Comment] = EmpData.Comment
![AddOns1] = EmpData.AddOns(1)
![AddOns2] = EmpData.AddOns(2)
![AddOns3] = EmpData.AddOns(3)
![Allowance1] = EmpData.Allowance(1)
![Allowance2] = EmpData.Allowance(2)
![Allowance3] = EmpData.Allowance(3)
![Contract] = EmpData.Contract
![CostCode] = EmpData.CostCode
![STHours] = EmpData.STHours
![OTHours] = EmpData.OTHours
![DTHours] = EmpData.DTHours
![WorkDate] = EmpData.WorkDate
![DateSubmitted] = SaveTime
'//Insert Record into Database
.Update
InsertMachineHoursRecord = True '//SUCCESSFUL INSERTION
End With
'//Note that we use recordset in this example, but equally effective
'// is to create an update query command text and simply run the update query:
'// (INSERT INTO Table (Field1, Field2) VALUES (Value1, Value2);
'//Make sure we have closed the database
My_Exit:
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
Exit Function
ErrHandler:
MsgBox Err.Description
Resume My_Exit
End Function