Execution error on with statement, but before all ran good - excel

I used this macro a few days ago and all worked well but now it does not work properly. I get an execution error at the very beginning of the with statement, or i get another automation error.
I checked if my file exists and it exists, checked if it's found or not: all ok but when i create the excel object and begin with statement i get an error
ActiveDocument.Application.ScreenUpdating = False
Dim strSite As Site, intRow As Long, rg As Object, tmp As String, lastCol As Long, i As Long 'varibles pour derniere colonne du fichier excel et la ligne de la trigramme recherche
Dim xlapp As Object, xlbook As Object, currentcell As Object, nextcell As Object, src As Object
Dim found As String, filename
'creation du objet Excel
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If err Then
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
filename = "FichierTrigrammes.xlsx"
found = Dir(folderPath & "\" & "FichierTrigrammes.xlsx")
MsgBox found
If found <> vbNullString Then
' to be changed to the real File Name, if not it will not work
Set xlbook = xlapp.workbooks.Open(filename:=folderPath & filename): xlapp.Visible = False 'does not open the file, read only => faster to get the info
' searching for the Trigramm
With xlbook.sheets(1)
intRow = xlbook.sheets(1).Cells.Find(what:=strTrigram).Row
'getting the address -> to get the row therafter
'find the last non blank cell in specific row
Set currentcell = xlbook.sheets(1).Range("a" & intRow)
Do While Not IsEmpty(currentcell)
Set nextcell = currentcell.Offset(0, 1)
If nextcell.Value = currentcell.Value Then
currentcell.EntireRow.Delete
End If
Set currentcell = nextcell
Loop
lastCol = .Range(currentcell.Address).Column
For i = 1 To lastCol
Select Case .Cells(1, i).Value
Case "Type Site"
strSite.type = .Cells(intRow, i).Value
Case "Nom Site"
strSite.nomSite = .Cells(intRow, i).Value
End Select
Next i
End With
'Set xlapp = Nothing: Set xlbook = Nothing ' pour ne pas sauvegarder le document
End If
ActiveDocument.Application.ScreenUpdating = True
getSiteInfo = strSite
End Function

First issue
If you use the Range.Find method it might be that nothing is found so you will always need to test for that case.
You need always to specify the LookAt parameter for Find as xlWhole or xlPart otherwise VBA will use whatever the user or VBA used before (there is no default). If you don't specify it you never know what you get.
So something like this:
Dim FoundAt As Range
'…
FoundAt = xlbook.sheets(1).Cells.Find(What:=strTrigram, LookAt:=xlWhole)
If Not FoundAt Is Nothing Then '
intRow = FoundAt.Row
'All your other code
Else
MsgBox "'" & strTrigram & "' was not found."
End If
If you use Late Binding in Word then define the following constants:
Const xlWhole As Long = 1
Const xlPart As Long = 2
to make them available in Word.
Second issue
Note that with the following code both Set xlapp might fail and both errors will be hidden because of On Error Resume Next.
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If err Then
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
Change it to
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
On Error GoTo 0
If xlapp Is Nothing Then
Set xlapp = CreateObject("Excel.Application")
End If
Third issue
You test if folderPath & "\" & "FichierTrigrammes.xlsx" exists but you open something different folderPath & filename.
Change it to
filename = "FichierTrigrammes.xlsx"
found = Dir(folderPath & Application.PathSeparator & filename)
and use that to open the file
Set xlbook = xlapp.workbooks.Open(filename:=folderPath & Application.PathSeparator & filename)

Related

Finding last row throws an object required error

What I am trying to do.
I highlight some text in an email then run my macro.
It 'copies' the highlighted text and stores it in variable strText.
Then it creates a file called Artwork List.xlsx if it does not exist and if it exists it opens it.
After that it copies the text into the file in column A row 1 if the lastrow is 1, and if not, it appends to lastrow + 1
My code throws
'Run-time error 424, Object required'
To narrow down, the error should be coming from:
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
or anything related to this line.
Sub copyArts2File()
MsgBox "ok"
Dim OutApp As Object
Dim OutMail As Object
Dim olInsp As Object
Dim wdDoc As Object
Dim strText As String
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim strTextArr As Variant
On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")
'Outlook wasn't running, so cancel
If Err <> 0 Then
MsgBox "Outlook is not running so nothing can be selected!"
GoTo lbl_Exit
End If
On Error GoTo 0
Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)
With OutMail
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
strText = wdDoc.Application.Selection.Range.Text
End With
'MsgBox strText
lbl_Exit:
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
FileName = "Artwork List.xlsx"
fileDoesExist = Dir("C:\Users\quaer\Desktop\DL Arts\" & FileName) > ""
' Check for existing file
If fileDoesExist Then
' Open Excel file
Set xlBook = xlApp.Workbooks.Open("C:\Users\quaer\Desktop\DL Arts\" & FileName)
Set xlSheet = xlBook.Sheets(1)
Else
' Add Excel file
Set xlBook = xlApp.Workbooks.Add
With xlBook
.SaveAs FileName:="C:\Users\quaer\Desktop\DL Arts\" & FileName
End With
Set xlSheet = xlBook.Sheets(1)
End If
' Do stuff with Excel workbook
Dim i As Integer
Dim lastrow As Long
With xlApp
With xlBook
With xlSheet
strTextArr = Split(strText, "Adding file")
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastrow
If lastrow = 1 Then
For i = 1 To UBound(strTextArr)
.Range("A" & i).Value = strTextArr(i)
Next i
Else
For i = 1 To UBound(strTextArr)
.Range("A" & (i + lastrow)).Value = strTextArr(i)
Next i
End If
.Close SaveChanges:=True
End With
End With
End With
xlApp.Visible = True
Exit Sub
End Sub
Try replacing this line, lastrow = .Cells(Rows.Count, 1).End(xlUp).Row, with:
lastrow = .Cells(1048576, 1).End(xlUp).Row
or
lastrow = .Cells(Rows.Count +1, 1).End(xlUp).Row
Jeeez this is crazy. I have found the problem finally and got a working code for anyone wanting similar usage. 1st off, I need to add the Microsoft excel add in. So in Outlook VBA, Tools -> references -> check Microsoft Excel 16.0 Object Library. This is to get rid of the 424 object required error, as I was trying to a call a excel built in method I guess. this is the line:
lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
Pls note that I am calling this macro from Outlook.
After this I faced a couple of other issues.
1. errors such as 424 run time, remote server machine does not exist or is not available.
first time running, it throws this error, 2nd time I click, the problem goes away. This is an issue with non specific use of the app, book and worksheet and so leaves VBA to assign on its own. Lesson learnt, be explicit about every thing.
leaves a copy of excel process even after program ends. This can be seen in task manager. This causes issues because then my excel file is linked to this process and not able to open without either read only or notify. Its locked with the process. So I cannot run again next time.
Anyway. Here is the final code. And I have also changed it to .Range instead of .Cells. I believe it does not matter if I used either but the key culprit is : xlSheet.Rows.Count. Instead of just Rows.Count, explicitly use xlSheet.Rows.Count.
Option Explicit
Sub copyArts2File()
MsgBox "ok"
Dim OutApp As Object, OutMail As Object, olInsp As Object, wdDoc As Object
Dim xlApp As Excel.Application, xlBook As Excel.Workbook, xlSheet As Object
Dim strText As String
Dim strTextArr As Variant
Dim fName As String
Dim fileDoesExist As Boolean
Dim i As Integer
Dim lastrow As Long
On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")
'Outlook wasn't running, so cancel
If Err <> 0 Then
MsgBox "Outlook is not running so nothing can be selected!"
GoTo lbl_Exit
End If
On Error GoTo 0
Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)
With OutMail
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
strText = wdDoc.Application.Selection.Range.Text
End With
'MsgBox strText
'Close out all shit
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
lbl_Exit:
Set OutMail = Nothing
Set OutApp = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
On Error Resume Next 'Create or use a Excel Application
Set xlApp = GetObject(, "Excel.Application")
If Err.Number > 0 Then Set xlApp = CreateObject("Excel.Application")
On Error GoTo 0
xlApp.Visible = False
xlApp.DisplayAlerts = False
fName = "Artwork List.xlsx"
fileDoesExist = Dir("C:\Users\quaer\Desktop\DL Arts\" & fName) > ""
' Check for existing file
If fileDoesExist Then
' Open Excel file if present
Set xlBook = xlApp.Workbooks.Open("C:\Users\quaer\Desktop\DL Arts\" & fName)
Else
' Add Excel file if not present
Set xlBook = xlApp.Workbooks.Add
xlBook.SaveAs fileName:="C:\Users\quaer\Desktop\DL Arts\" & fName
End If
Set xlSheet = xlBook.Worksheets(1)
' Do stuff with Excel workbook
strTextArr = Split(strText, "Adding file")
lastrow = xlSheet.Range("A" & xlSheet.Rows.Count).End(xlUp).Row
If lastrow = 1 Then
For i = 1 To UBound(strTextArr)
xlSheet.Range("A" & i).Value = strTextArr(i)
Next i
Else
For i = 1 To UBound(strTextArr)
xlSheet.Range("A" & (i + lastrow)).Value = strTextArr(i)
Next i
End If
xlBook.SaveAs fileName:="C:\Users\quaer\Desktop\DL Arts\" & fName, AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
xlBook.Close (True)
Set xlBook = Nothing
Set xlSheet = Nothing
xlApp.Visible = True
xlApp.Quit
Set xlApp = Nothing
MsgBox "Done!"
Exit Sub
End Sub
Thanks for the help and suggestions nonetheless.

Find only whole word, not the part of a word from Excel Workbook

I am working from MS Word to extract data from an Excel Workbook:
Sub Birthyard()
Dim xlapp As Object
Dim xlbook As Object
Dim xlsheet As Object
Dim SWORD As Range
Set SWORD = Selection.Paragraphs(1).Range
SWORD.MoveEnd wdCharacter, -1
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If Err Then
bstartApp = True
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
With xlapp
Set xlbook = .Workbooks.Open("C:\users\ibnea\Desktop\list.xlsm")
Set RANG = xlbook.Worksheets("Sheet4").Range("A:B").Find(SWORD)
If RANG Is Nothing Then
MsgBox "Nothing Found in Sheet4 Range(A:B)"
Else
If RANG.Column = "2" Then
COMPANY = RANG.Offset(0, -1).Value
TICKER = RANG.Value
MsgBox COMPANY & TICKER
Else
COMPANY = RANG.Value
TICKER = RANG.Offset(0, 1).Value
MsgBox COMPANY & TICKER
End If
End If
End With
If bstartApp = True Then
xlapp.Quit
End If
Set xlapp = Nothing
Set xlbook = Nothing
Set xlsheet = Nothing
End Sub
Above code opens an Excel Workbook and finds a given word from the first two columns. The problem lies when text found is part of a word.
For example, if the search word/criteria contains a small string such as "be" or "sp" then I get several of false results. I need the function to stop looking within the words and look at the word as a whole for a match.
I found that it will be done by adding a trim Function, and regex is a thing that does the job. I don't know how to handle these functions.
loop thorugh all found occurrences till you meet the one with the keyword as a single word:
here is the relevant snippet:
With xlbook.Worksheets("Sheet4").Range("A:B")
Set RANG = .Find(what:=SWORD, lookat:=xlPart, LookIn:=xlValues)
If Not RANG Is Nothing Then
Dim firstAddress As String
firstAddress = RANG.Address
Do
If Not IsError(Application.Match(SWORD, Split(RANG, " "), 0)) Then
MsgBox "found " & SWORD & " in " & RANG.Address
' do what you need with RANG object
Exit Do
End If
Set RANG = .FindNext(RANG)
Loop While RANG.Address <> firstAddress
End If
End With
Find Whole Word in Cells of a Range
The search (Find) is done by rows i.e. A1, B1, A2, B2 , A3, B3... If you want it done by column, change xlByRows to xlByColumns (A1, A2, A3 ... B1, B2, B3...).
The FindWord subroutine searches each found cell containing the word (SWORD) for an occurrence of the whole word (SWORD).
The Code
Sub Birthyard()
Dim xlapp As Object
Dim xlbook As Object
Dim xlsheet As Object
Dim SWORD As Range
Dim vntRng As Variant
Dim intCount As Integer
Dim blnFound As Boolean
Dim strFirst As String
Set SWORD = Selection.Paragraphs(1).Range
SWORD.MoveEnd wdCharacter, -1
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If Err Then
bstartApp = True
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
With xlapp
Set xlbook = .Workbooks.Open("C:\users\ibnea\Desktop\list.xlsm")
With xlbook.Worksheets("Sheet4").Range("A:B")
Set RANG = .Find(SWORD, .Cells(.Rows.Count, .Columns.Count), _
xlValues, xlPart, xlByRows)
If Not RANG Is Nothing Then
GoSub FindWord
If blnFound = False Then
strFirst = RANG.Address
Do
Set RANG = .FindNext(RANG)
Debug.Print RANG.Address
GoSub FindWord
Loop While Not blnFound = True And RANG.Address <> strFirst
End If
End If
If blnFound Then
If RANG.Column = "2" Then
COMPANY = RANG.Offset(0, -1).Value
TICKER = RANG.Value
MsgBox COMPANY & TICKER
Else
COMPANY = RANG.Value
TICKER = RANG.Offset(0, 1).Value
MsgBox COMPANY & TICKER
End If
Else
MsgBox "Nothing Found in Sheet4 Range(A:B)"
End If
End With
If bstartApp = True Then
.Quit
End If
End With
Set xlapp = Nothing
Set xlbook = Nothing
Set xlsheet = Nothing
Exit Sub
FindWord:
vntRng = Split(RANG.Value)
For intCount = 0 To UBound(vntRng)
If vntRng(intCount) = SWORD Then Exit For
Next
If intCount <= UBound(vntRng) Then
blnFound = True
End If
Return
End Sub

Return Excel Row in Word Macro

I have ContentControl drop down box in Word. Once I select an item from a Drop Down list I want to search for that in an Excel document and set the row number equal to a variable.
The code below is what I tried but the Columns("G:G").Find part says its not defined.
Sub findsomething(curRow)
Dim rng As Range
Dim rownumber As Long
curPath = ActiveDocument.path & "\"
Call Set_Variable(curPath)
StrWkShtNm = "Chapters"
If Dir(StrWkBkNm) = "" Then
MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
Exit Sub
End If
Set rng = Columns("G:G").Find(what:=curRow)
rownumber = rng.Row
MsgBox rownumber
' Release Excel object memory
Set xlWkBk = Nothing
Set xlApp = Nothing
Application.ScreenUpdating = True
End Sub
While using more than one MS Office application it is a good idea to specify which application you are targeting:
Excel.Application.ThisWorkbook.Sheets(1).Range("A1").Select
this is what ended up working. you set me on the right track with referencing Excel.
Sub findsomething(curRow)
Dim rng As Long
Dim rownumber As Long
curPath = ActiveDocument.path & "\"
Call Set_Variable(curPath)
StrWkShtNm = "Chapters"
MsgBox "curRow = " & curRow
If Dir(StrWkBkNm) = "" Then
MsgBox "Cannot find the designated workbook: " & StrWkBkNm, vbExclamation
Exit Sub
End If
With xlApp
.Visible = False
Set xlWkBk = .Workbooks.Open(FileName:=StrWkBkNm, ReadOnly:=True, AddToMRU:=False)
With xlWkBk
With .Worksheets(StrWkShtNm)
rng = .Range("G:G").Find(what:=curRow)
MsgBox rng
End With
.Close False
End With
.Quit
End With
' Release Excel object memory
Set xlWkBk = Nothing: Set xlApp = Nothing
Application.ScreenUpdating = True
End Sub

Orphaned Excel Process with Outlook VBA

I am having trouble ending the Excel process that I call open with Outlook VBA.
I have looked into a few solutions like setting variables to Nothing at the end and using With statements after all variables.
The orphaned process seems to be causing problems when I call Excel over and over again.
The code is suppose to download the attachment, copy some cell values into a workbook, save and close the documents.
Private WithEvents myOlItems As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set myOlItems = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub myOlItems_ItemAdd(ByVal item As Object)
Dim Msg As Outlook.MailItem
Dim msgattach As Object
Dim wb As Workbook
Dim myXLApp As Excel.Application
Dim filepath As String
Dim filepathone As String
Dim filepathtwo As String
Dim wbhome As Worksheet
Dim comp As String
Dim wbtemp As Workbook
Dim testcode As Workbook
Dim matrix As Worksheet
Dim testflr As Worksheet
If TypeName(item) = "MailItem" Then
Set Msg = item
If Left(Msg.Subject, 14) = "SES Gas Matrix" Then
Set myXLApp = CreateObject("Excel.Application")
myXLApp.DisplayAlerts = False
If Msg.Attachments.Count <> 0 Then
For Each msgattach In Msg.Attachments
If Right(msgattach.FileName, 5) = ".xlsx" Then
filepath = "G:\Betts\Floor Matricies\FIFOs\" & Format(Now(), "YYYYMMDD") & " - " & "Gas Rates" & Right(msgattach.FileName, 5)
msgattach.SaveAsFile filepath
End If
Next
End If
Set msgattach = Nothing
Set wbtemp = Workbooks.Open(filepath, UpdateLinks:=3)
Set matrix = wbtemp.Sheets("Sheet1")
wbtemp.Activate
filepathtwo = Left(filepath, Len(filepath) - 5)
matrix.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
filepathtwo & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
filepathone = "http://intranet/Pricing%20and%20Rates/Floor%20Matrices/FIFOs/" & Format(Now(), "YYYYMMDD") & "%20-%20Gas%20Rates.pdf"
matrix.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
filepathone _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Dim rangeb5l9 As Range
Set rangeb5l9 = matrix.Range("B5:L9")
rangeb5l9.Copy
Set rangeb5l9 = Nothing
On Error GoTo ErrorHandler
Set testcode = Workbooks.Open(FileName:="G:\Betts\ReturnOnInvestment_Master_Backup Testcode.xlsm", UpdateLinks:=3)
Set testflr = testcode.Sheets("Floor Pricing")
Dim rangea44 As Range
Dim rangeb93 As Range
Dim rangeb94 As Range
Set rangea44 = testflr.Range("A44")
rangea44.PasteSpecial xlPasteValues
myXLApp.CutCopyMode = False
Set rangea44 = Nothing
Set rangeb93 = testflr.Range("B93")
rangeb93 = "Yes"
wbtemp.Close
Set wbtemp = Nothing
Kill (filepath)
Set rangeb94 = testflr.Range("B94")
If rangeb93 = "Yes" And rangeb94 = "Yes" Then
testcode.Application.Run ("Module34.OFVT")
rangeb93 = "No"
rangeb94 = "No"
End If
Set rangeb94 = Nothing
Set rangeb93 = Nothing
Set testflr = Nothing
testcode.Close savechanges:=True
Set testcode = Nothing
Set matrix = Nothing
myXLApp.DisplayAlerts = True
myXLApp.Quit
Set myXLApp = Nothing
Msg.UnRead = False
End If
Set Msg = Nothing
End If
'test area
Set item = Nothing
Exit Sub
ErrorHandler:
If (Err.Number = 50290) Then Resume
Stop
Resume
End Sub
There are a few recommended rules that you could apply in this kind of applications.
1- Before opening Excel, check if Excel is already open and get the running instance. You can create a custom routine to do that:
Function getExcelApp() As Excel.Application
On Error Resume Next
Set getExcelApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then Set getExcelApp = CreateObject("Excel.Application")
End Function
2- Make the application visible, at least in the phase where you're still writing and debugging your code.
Set myXLApp = getExcelApp ' <-- get it or create it
myXLApp .Visible = true ' <-- useful at least in the development phase
3- You can eventually shortcut the two-phases (create app, open doc) with just one step
Dim wb as Excel.Workbook
Set wb= GetObject(filepath)
This will either get an already open document instance or open it if not. You can later get the Application Object as wb.Application.
4- Make sure you correctly handle the error situations to that all paths will close the Excel application, including those resulting from an error.
5- Since the application you're using is temporary, keep it with DisplayAlerts = False state. As I see you reset it to DisplayAlerts = true before quitting. This is source of headache. Imagine the "non-visible" application blocked with some alert messagebox? I suggest you drop that line (keep false).
6- Qualify your ranges and object variables
Set wbtemp = myXlApp.Workbooks.Open(filepath, 3, True) '<-- better than using the unqualified Workbooks

Access - open Excel file, do some coding with It and close

I'm trying to open an Excel file from Access and do some stuff with It, but code is not stable. Sometimes It works, other times not. Here's how I do this:
Dim FilePath As String
Dim ExcelApp As Excel.Application
FilePath = "C:\Users\Lucky\Desktop\Test.xls"
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Workbooks.Open (FilePath)
With ExcelApp
'do some stuff here
End With
ExcelApp.Workbooks.Close
Set ExcelApp = Nothing
I've also noticed that once I run code, Excel starts proccess under Task Manager, that has to be killed manually in order to get code working again. Otherwise I get two types of error with Excel file:
one is that If I click Excel file, It doesn't open, It just flashes for a second and dissapears
and other is that Excel file opens in "read-only" mode...
So I reckon there is some flaw when file is closed in my code. How can I fix this ?
I can't see what's wrong with your code - maybe the path to the desktop?
This is the code I usually use - I've added another function to help choose the file. It uses late binding, so no need to set a reference to Excel - you don't get the IntelliSense and can't use Excel constants such as xlUp - you have to use the numerical equivalent.
Public Sub Test()
Dim oXLApp As Object
Dim oXLWrkBk As Object
Dim oXLWrkSht As Object
Dim vFile As Variant
Dim lLastRow As Long
vFile = GetFile()
Set oXLApp = CreateXL
Set oXLWrkBk = oXLApp.WorkBooks.Open(vFile, False)
Set oXLWrkSht = oXLWrkBk.WorkSheets(1) 'First sheet. Can also use "Sheet1", etc...
lLastRow = oXLWrkSht.Cells(oXLWrkSht.Rows.Count, "A").End(-4162).Row '-4162 = xlUp
MsgBox "Last row in column A is " & lLastRow
oXLWrkBk.Close False
oXLApp.Quit
Set oXLWrkBk = Nothing
Set oXLApp = Nothing
End Sub
Public Function CreateXL(Optional bVisible As Boolean = True) As Object
Dim oTmpXL As Object
'''''''''''''''''''''''''''''''''''''''''''''''''''''
'Defer error trapping in case Excel is not running. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
Set oTmpXL = GetObject(, "Excel.Application")
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
'If an error occurs then create an instance of Excel. '
'Reinstate error handling. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Err.Number <> 0 Then
Err.Clear
On Error GoTo ERROR_HANDLER
Set oTmpXL = CreateObject("Excel.Application")
End If
oTmpXL.Visible = bVisible
Set CreateXL = oTmpXL
On Error GoTo 0
Exit Function
ERROR_HANDLER:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure CreateXL."
Err.Clear
End Select
End Function
Function GetFile(Optional startFolder As Variant = -1, Optional sFilterName As String = "") As Variant
Dim fle As Object
Dim vItem As Variant
'''''''''''''''''''''''''''''''''''''''''''
'Clear the file filter and add a new one. '
'''''''''''''''''''''''''''''''''''''''''''
Application.FileDialog(3).Filters.Clear
Application.FileDialog(3).Filters.Add "'Some File Description' Excel Files", "*.xls, *.xlsx, *.xlsm"
Set fle = Application.FileDialog(3)
With fle
.Title = "Select a file"
.AllowMultiSelect = False
If startFolder = -1 Then
.InitialFileName = CurrentProject.Path
Else
If Right(startFolder, 1) <> "\" Then
.InitialFileName = startFolder & "\"
Else
.InitialFileName = startFolder
End If
End If
If .Show <> -1 Then GoTo NextCode
vItem = .SelectedItems(1)
End With
NextCode:
GetFile = vItem
Set fle = Nothing
End Function
I have managed to solve my problem. There is nothing wrong with code in my question, except that instead of declaring
Dim ExcelApp As Excel.Application
It's better to use
Dim ExcelApp As Object
But much bigger problem is with code that does changes in Excel, such as this line:
x = Range(Cells(1, i), Cells(Rows.Count, i).End(xlUp)).Value
And correct synthax is:
x = ExcelApp.Range(ExcelApp.Cells(1, i), ExcelApp.Cells(ExcelApp.Rows.Count, i).End(xlUp)).Value 'maybe also better to replace xlUp with -4162
So, whenever you use some code for Excel file from Access, DON'T FORGET to reference everything to Excel object. And ofcourse, before everything, a proper reference must be set in VBA console, in my case Microsoft Office 15.0 library.

Resources