Weird Access open issue

mahmed1

Well-known Member
Joined
Mar 28, 2009
Messages
2,302
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
Hi guys

I am running some code from Excel that opens up access Runs 2 macros in the Access Database and then paste into my excel sheet using the open
Recordeset (dont have the code to had at present) but my main issue is that
When some users run it it comes up with a msg that the database is open even though i can assure you that it aint open but if i or some users run it, it runs fine...

so for some users it runs and others that the access DB is open and i just dont why

i have closed all access down and even ended task for access for the users affected and myself and same thing happens

it doesnt like it when they or certain users run it

my code just opens Access Dn
Calls the AccessUpdateMacro
 

Excel Facts

Round to nearest half hour?
Use =MROUND(A2,"0:30") to round to nearest half hour. Use =CEILING(A2,"0:30") to round to next half hour.
Post your code - in code tags.
 
Upvote 0
Hi JonXL - so here are the VBA codes that is called from Excel and Access - So from Excel I do some updates to the access database - and in Access i open up the recordset and update to the relevant sheets in the excel workbook that called the macro from Access. Again multiple users can be trying to connect to the database at the same time so i have a msgbox to ensure if its open the user tries again - it would be awesome if they can open at same time with out any issues. Again this works but some users get msg that access is open but if i run it it runs fine.

Is it better to put accessapp.quit to ensure access is fully closed as often im having to end task on the access app if its opened in the background...

Excel VBA Code

VBA Code:
Sub RefreshAll_Button_Click()

Dim dStart As Double, dEnd As Double
Dim lRowCurr As Long
Dim rsCurr As Recordset
Dim sqlQuery As String
Dim ctCurr As Integer, ctSetCurr As Integer, fromDate As String, toDate As String
Dim wbName As String
wbName = ThisWorkbook.Name
'MsgBox wbName
dStart = Now

Call TurnOffStuff
Call DeleteData

Application.StatusBar = "Database Updating"

    Dim appAccess As New Access.Application
    Set appAccess = Access.Application

On Error GoTo errormsg
    appAccess.OpenCurrentDatabase ThisWorkbook.Worksheets("CONTROLS").Range("L2").Value
    
    sqlQuery = "INSERT INTO WorkbookLog VALUES ('" & wbName & "', CDate('" & Now & "'))"
    appAccess.DoCmd.RunSQL (sqlQuery)
    appAccess.Run "GetNewData"
    
    
    appAccess.CloseCurrentDatabase
    
    Set appAccess = Nothing
    
    Set appAccess = New Access.Application

    On Error GoTo errormsg
    appAccess.OpenCurrentDatabase ThisWorkbook.Worksheets("CONTROLS").Range("L3").Value

    appAccess.Run "GetNewData"
    ThisWorkbook.Connections("tbl_Shrinkage_MU_Set").Refresh
    appAccess.CloseCurrentDatabase
    
    Application.StatusBar = "Database Updated"
    
    Set appAccess = Nothing
    Set fs = Nothing

Call TurnOnStuff
Call UpdateIndirectFormulaValues

Application.Goto ThisWorkbook.Worksheets("Inputs and Outputs").Range("A1"), True

dEnd = Now

Application.StatusBar = ""

MsgBox "Completed in: " & Format(dEnd - dStart, "hh:mm:ss"), vbOKOnly, "Database Updated"

Exit Sub

errormsg:
    Set appAccess = Nothing
    MsgBox "The update is being run by another user, try again in a minute", vbOKOnly, "Database Alert"
On Error GoTo 0

End Sub

FULL ACCESS VBA CODE

VBA Code:
Public Sub GetNewData()

    DoCmd.SetWarnings (False)

    Dim fs As FileSystemObject
    Dim f As Object
    Dim FileArray() As String
    Dim FileToDoArray() As String
    Dim FileTimeArray() As Double
    Dim DatabaseTimeArray() As Double
    Dim qryTemp As String
    Dim rs As Object
    Dim entryCount As Integer
    Dim Size As Double
    Dim Size2 As Double
    Dim dStart As Double
    Dim dEnd As Double
    
    dStart = Now
    
    Pause (1)
    
    DoCmd.SetWarnings (False)
    
    qryTemp = "SELECT DISTINCT a.FileName, a.DateTime" & _
                " FROM ImportLog a WHERE a.DateTime = (SELECT MAX(b.DateTime) FROM ImportLog b WHERE b.FileName = a.FileName GROUP BY FileName) ORDER BY DateTime DESC"
    
    Set rs = CurrentDb.OpenRecordset(qryTemp)
    Set fs = New FileSystemObject
    
    entryCount = rs.RecordCount
    
    ReDim FileArray(entryCount - 1)
    ReDim DatabaseTimeArray(entryCount - 1)
    ReDim FileTimeArray(entryCount - 1)
    
    i = 0
    If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst
        Do Until rs.EOF = True
            
            FileArray(i) = rs.Fields("FileName").Value
            DatabaseTimeArray(i) = rs.Fields("DateTime").Value
            Set f = fs.GetFile("\\st1w3105\results\" & rs.Fields("FileName").Value & ".txt")
            FileTimeArray(i) = f.DateLastModified
            If f.DateLastModified > DatabaseTimeArray(i) Then
                ReDim Preserve FileToDoArray(i)
                FileToDoArray(i) = FileArray(i)
            End If
            i = i + 1
            rs.MoveNext
        Loop
    End If
    
    rs.Close
    Set rs = Nothing
    
    If IsEmpty(FileToDoArray()) Then
        GoTo endprocess
    End If
    
    
    On Error GoTo endprocess
    For Each i In FileToDoArray()
        If i = "" Then
        Else
        Set f = fs.GetFile("\\st1w3105\results\" & i & ".txt")
        Size = f.Size / 1024
        If Size < 1 Then
            Do While Size < 1
                Size = f.Size / 1024
                If Now > dStart + #12:05:00 AM# Then
                    GoTo getoutofloop
                End If
            Loop
        End If
        Pause (1)
        Size2 = f.Size / 1024
        Do While Not Size2 = Size
                Size = f.Size / 1024
                Pause (1)
                Size2 = f.Size / 1024
                If Now > dStart + #12:06:00 AM# Then
                    GoTo getoutofloop
                End If
        Loop
        End If
    Next
    
    For Each i In FileToDoArray()
        If i = "" Then
        Else
        DoCmd.RunSavedImportExport ("Import-" & i)
        End If
    Next
    
getoutofloop:
    
    Delete_tbl
    DoCmd.RunSQL "DELETE * FROM WFM_Plan_Forecast WHERE Date_ IS NULL"
    DoCmd.RunSQL "UPDATE WFM_Plan_Forecast SET THT = fcstContactsReceived * fcstAHT, [Datetime] = CDate(CStr([Date_]) & ' ' & Period & ':00')"
    DoCmd.RunSQL "UPDATE WFM_Plan_Forecast AS t INNER JOIN tbl_Entity_Sets AS ent ON t.ctID = ent.ctID SET t.Entity_Set_ID = ent.Entity_Set_ID, t.Entity_Set = ent.Entity_Set"
    DoCmd.RunSQL "DELETE * FROM tbl_CT_All_Forecast"
    DoCmd.RunSQL "INSERT INTO tbl_CT_All_Forecast SELECT Datetime, Date_ AS [Date], Period AS Period, ctID AS ctID, ctName AS ctName, acdID AS acdID, fcstContactsReceived AS fcstContactsReceived, fcstContactsHandled AS fcstContactHandled, fcstAHT AS fcstAHT, fcstSLPct AS fcstSLPct, fcstOcc AS fcstOcc, fcstASa AS fsctASa, fcstReq AS fcstReq, revPlanReq AS revPlanReq, commitPlanReq AS commitPlanReq, schedOpen AS schedOpen, THT, Entity_Set_ID, Entity_Set FROM WFM_Plan_Forecast WHERE fcstContactsReceived > 0"
    
    qryTemp = "SELECT DISTINCT fcst.ctID, fn.FileName FROM WFM_Plan_Forecast fcst INNER JOIN tbl_Entity_Sets fn ON fcst.ctID = fn.ctID"
    
    Set rs = CurrentDb.OpenRecordset(qryTemp)
    entryCount = rs.RecordCount

        Do Until rs.EOF = True
            a = Format(rs.Fields("FileName").Value, "@")
            DoCmd.RunSQL "INSERT INTO ImportLog VALUES (Now, GetUserName(), " & rs.Fields("ctID").Value & ", " & Chr(34) & a & Chr(34) & ")"
            rs.MoveNext
        Loop
        
    rs.Close
    Set rs = Nothing
    
    DoCmd.RunSQL "DELETE * FROM WFM_Plan_Forecast"

    
    qryTemp = "SELECT DISTINCT fcst.ctID, fn.FileName FROM WFM_Plan_Forecast fcst INNER JOIN tbl_Entity_Sets fn ON fcst.ctID = fn.ctID"
    
    DoCmd.SetWarnings (True)
    
    dEnd = Now

endprocess:

    For Each i In Array("tbl_MCT_CALL", "tbl_CT_CALL_1", "tbl_CT_CALL_2", "tbl_CT_CALL_3")
        Dim xlApp As Excel.Application
        Dim wb As Excel.Workbook
        Dim ws As Excel.Worksheet
        Dim w As Variant
    On Error GoTo skipupdate
        
        Set xlApp = GetObject(, "Excel.Application")
        qryTemp = "SELECT TOP 1 WorkbookName FROM WorkbookLog ORDER BY Time Desc"
        
        Set rs = CurrentDb.OpenRecordset(qryTemp)
        entryCount = rs.RecordCount

        Do Until rs.EOF = True
            a = Format(rs.Fields("WorkbookName").Value, "@")
            wbname = a
            rs.MoveNext
        Loop
        
        rs.Close
        Set rs = Nothing
On Error GoTo errorcatch
        Set wb = xlApp.Workbooks(wbname)
        wb.Sheets(i).Activate
        Set ws = wb.Sheets(i)
        If i = "tbl_MCT_CALL" Then
            ctSetCurr = ws.Range("B1")
            ctCurr = 0
            fromdate = Format(ws.Range("B2"), "dd/mm/yyyy")
            todate = Format(ws.Range("B3"), "dd/mm/yyyy")
        Else
            ctSetCurr = ws.Range("C1")
            ctCurr = ws.Range("B1")
            fromdate = Format(ws.Range("B2"), "dd/mm/yyyy")
            todate = Format(ws.Range("B3"), "dd/mm/yyyy")
        End If
        
        If ctCurr = 0 Then
            qryTemp = "SELECT ct.[Datetime], MAX(ct.[Date]), MAX(ct.Period), MAX(ct.Entity_Set_ID), MAX(ct.Entity_Set)," & _
                        " SUM(ct.fcstContactsReceived), SUM(ct.THT)/SUM(ct.fcstContactsReceived) AS AHT, SUM(ct.SchedOpen) FROM tbl_CT_All_Forecast AS ct" & _
                        " WHERE (ct.Entity_Set_ID = " & ctSetCurr & ") AND ct.Date >= #" & Format(DateValue(fromdate), "yyyy\/mm\/dd") & "# And ct.Date <= #" & Format(DateValue(todate), "yyyy\/mm\/dd") & "#" & _
                        "GROUP BY ct.[Datetime]"
        Else
            qryTemp = "SELECT tbl_CT_All_Forecast.[Datetime], tbl_CT_All_Forecast.[Date], tbl_CT_All_Forecast.Period, tbl_CT_All_Forecast.Entity_Set, tbl_CT_All_Forecast.Entity_Set_ID, tbl_CT_All_Forecast.ctID, tbl_CT_All_Forecast.fcstContactsReceived, tbl_CT_All_Forecast.fcstAHT, tbl_CT_All_Forecast.schedOpen" & _
                       " FROM tbl_CT_All_Forecast" & _
                       " WHERE tbl_CT_All_Forecast.Date >= #" & Format(DateValue(fromdate), "yyyy\/mm\/dd") & "# And tbl_CT_All_Forecast.Date <= #" & Format(DateValue(todate), "yyyy\/mm\/dd") & "# AND (tbl_CT_All_Forecast.ctID= " & ctCurr & ")"
        End If

        Set rs = CurrentDb.OpenRecordset(qryTemp, , 4)
        Dim lRS As Long
        lRS = rs.RecordCount

        ws.Range("B6").CopyFromRecordset rs, lRS, 15
        Set rs = Nothing
        
        
    Next
skipupdate:
On Error GoTo errorcatch
    Erase FileToDoArray()

Exit Sub
errorcatch:
    CurrentDb.Close
End Sub

Public Function GetUserName() As String
    GetUserName = UCase(CreateObject("WScript.Network").UserName)
End Function

Sub Delete_tbl()
    Dim t As Object
    For Each t In CurrentDb.TableDefs
        If t.Name Like "*ImportErrors*" Then DoCmd.RunSQL ("DROP TABLE " & t.Name)
    Next
End Sub

Public Function Pause(NumberOfSeconds As Variant)
    On Error GoTo Error_GoTo

    Dim PauseTime As Variant
    Dim Start As Variant
    Dim Elapsed As Variant

    PauseTime = NumberOfSeconds
    Start = Timer
    Elapsed = 0
    Do While Timer < Start + PauseTime
        Elapsed = Elapsed + 1
        If Timer = 0 Then

            PauseTime = PauseTime - Elapsed
            Start = 0
            Elapsed = 0
        End If
        DoEvents
    Loop

Exit_GoTo:
    On Error GoTo 0
    Exit Function
Error_GoTo:
    Debug.Print Err.Number, Err.Description, Erl
    GoTo Exit_GoTo
End Function
 
Upvote 0
So after testing and even trying to open up with shell method - i found that some users are having issues with running these 2 lines of code

I get 2 errors

appAccess.OpenCurrentDatabase ThisWorkbook.Worksheets("CONTROLS").Range("L2").Value

sqlQuery = "INSERT INTO WorkbookLog VALUES ('" & wbName & "', CDate('" & Now & "'))"
appAccess.DoCmd.RunSQL (sqlQuery)

Error on DoCmd is 'run time error 2501 The RunSQL action was cancelled'

appAccess.Run "GetNewData"

Error here is 'run- time error 40351 method run of object- application failed
 
Upvote 0
Could you provide some general context:

What is the aim of this code?
How many users are using it and how often?
How long does it take to run?
What kind of data is being transferred from Excel to Access? From Access to Excel?
I guess you had better also say if you have a plan for regular compacts of your database since it looks like a lot of deleting going on.

Also it is clearly wrong to open an access application and not close it. The error handling looks very spotty because it isn't cleaning up the objects properly. If you open a database in code you should close it. If you open an Access application you should quit it (probably the latter does the closing too, but closing a database is not the same as quitting Access, and setting an Access object to nothing is also not a good way to quit).

Also I can't help but wonder what is the point of the filesize / 1024 looping - it doesn't appear to have any purpose. The fact that you have a pause in this code is also a red flag that you are try to work around some problem in the code.
 
Upvote 0
Could you provide some general context:

What is the aim of this code?
How many users are using it and how often?
How long does it take to run?
What kind of data is being transferred from Excel to Access? From Access to Excel?
I guess you had better also say if you have a plan for regular compacts of your database since it looks like a lot of deleting going on.

Also it is clearly wrong to open an access application and not close it. The error handling looks very spotty because it isn't cleaning up the objects properly. If you open a database in code you should close it. If you open an Access application you should quit it (probably the latter does the closing too, but closing a database is not the same as quitting Access, and setting an Access object to nothing is also not a good way to quit).

Also I can't help but wonder what is the point of the filesize / 1024 looping - it doesn't appear to have any purpose. The fact that you have a pause in this code is also a red flag that you are try to work around some problem in the code.

Thank you for your response

I really appreciate it so much

ok il try to answer all your questions the best i can..

There will be say around 10 people using this...

the aim was from excel, open up the access DB which has a macro in there to copy some a text file into the access table - it needs some deleting as the way the text files stored so im having to clean it up and then put into a final table

the pause was to get around the fact that the text file il be imported might not have been fully completed so i wait for it to be fully completed before it gets imported into the table and once done - it pastes into the worksheet of the excel doc that called the macro..

i wanted to make it quicker hence why i did everything in access so that excel just calls access macro that does everything

ok i didnt realise I didnt close access properly- can you be kind enough to show me where to add the quit code..please

after doing some reading - i realised that i had to go to trust centre settings for each agent who is running it and on their profile - open up the access database and allow the trust centre setting location and browse to the location of where the database is stored - its weird because it worked for me and a couple of others and we didnt have to do that

the other work around was i set a reference to the DAO object and used the execute method to run a piece of SQL

now i dont know why i had to do it...

regarding the code itself - can you advise of potentially making the code quiicker and also advise where to addquit code

i often yes have to do that compact thing and the size reduces massssively - this code can run multiple times during the day so is there a better way to get around this where i dont have to press the compact and do it in code or better coding to get around that?

i really hope i answered your questions properly
 
Upvote 0
The code to import takes around 3-4 minutes to import and clean up
 
Upvote 0
Actually looks strange too:
VBA Code:
    Dim appAccess As New Access.Application
    Set appAccess = Access.Application

I don't know what that does.

It should be:
VBA Code:
    Dim appAccess As Access.Application
    Set appAccess = New Access.Application
or just
VBA Code:
    Dim appAccess As New Access.Application

The way you quit is simple:

VBA Code:
appAccess.Quit

Are you saying the original basic problem (besides the many little problems) is solved by editing the trust center settings?
 
Upvote 0

Forum statistics

Threads
1,214,598
Messages
6,120,441
Members
448,966
Latest member
DannyC96

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top