Thanks for you both replying.
Sorry, attached is the entire code as well as a Pause function I tried using to maybe create a delay in the code (similar to the delay that would be caused by a MsgBox).
Code:
Option Compare DatabaseOption Explicit
Private Sub Command0_Click()
Dim xlApp As Object
Dim myPath As String
Dim myFile As String
Dim myFilePath As String
Dim myExtension As String
DoCmd.SetWarnings False
Application.Echo False
'create a way to run excel from access
Set xlApp = CreateObject("Excel.Application")
'set to look for excel files
myExtension = "*.xls"
'set path for folder containing files
myPath = "C:\Users\FileFolder\"
'finds the directory of the file based off path and extension
myFile = Dir(myPath & myExtension)
'collects full file name
myFilePath = myPath & myFile
Do While myFile <> ""
'opens the first workbook
xlApp.Workbooks.Open myFilePath
'pauses to make sure the workbook is open
Pause (2)
'insert edits to worksheet below
With xlApp
.Range("B12").Select
.Selection.Copy
.Range("K83:K87").Select
.ActiveSheet.Paste
.Range("B20").Select
.Application.CutCopyMode = False
.Selection.Copy
.Range("L83:L87").Select
.ActiveSheet.Paste
.Range("B21").Select
.Application.CutCopyMode = False
.Selection.Copy
.Range("M83:M87").Select
.ActiveSheet.Paste
.Range("B71").Select
.Application.CutCopyMode = False
.Selection.Copy
.Range("N83:N87").Select
.ActiveSheet.Paste
.Range("B82:N88").Select
.Selection.Copy
End With
'appends the selected range to the given table
DoCmd.OpenTable ("ACII")
SendKeys "^{a}"
DoCmd.RunCommand acCmdPasteAppend
DoCmd.Close acTable, "ACII", acSaveYes
'pauses again
Pause (2)
'selects the next file in the directory
myFile = Dir
Loop
MsgBox "Import Complete"
xlApp.Quit
Dim sKill As String
'Close excel Files
sKill = "TASKKILL /F /IM excel.exe"
Shell sKill, vbHide
'path of the folder that will contain the csv files and adds "archived" infront of their name
movPath = "C:\Users\ArchivedFolder\"
myFile = Dir(myPath & "\")
Do Until myFile = ""
Name myPath & myFile As movPath & myFile
myFile = Dir
Loop
MsgBox "Files Archived"
DoCmd.SetWarnings True
Application.Echo True
MsgBox "Update Complete"
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
' Crossing midnight
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
I'm going to try the suggestions above and report back. Last time I was able to run the code it worked 4 out of 5 times - still not sure why.