I am running a program where I have to open .xls files in a folder one by one and get information from them. At the beginning of my function I run this code below for each .xls file I want to open.
However, every once in a while, I get this error on the fourth line of code: 'ActiveX Component Can't Create Object'.
After clicking debug on the error window, I am able to just click continue and the code starts running fine. It opens the file and gets the info I want.
Why does this error come up? I don't want to keep clicking to progress this process.
Thanks in advance.
Function getPerfumeName(file)
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(file)
phrase = Split(WBK.Sheets(1).Cells(3, 1).Value, ":")
If phrase(0) = "PERFUME GCAS" Then
getPerfumeName = phrase(UBound(phrase))
Else
getPerfumeName = ""
End If
WBK.Close
Set XL = Nothing
End Function
I run this code below for each .xls file I want to open.
Maybe becuase you are creating too many of them? Outside the loop, use that only once and then inside the loop use Set WBK = XL.Workbooks.Open(file)
to open the file and then close the file before the loop ends... Also since you ar eusing Early Binding, you may use Dim XL As New Excel.Application
once outside the loop and it will work. No need to use both the lines...
Sub Sample()
Dim XL As New Excel.Application
Dim WBK As Excel.Workbook
For i = 1 To whatever
Set WBK = XL.Workbooks.Open(file)
'
'~~> Do Something
'
WBK.Close (False) 'or WBK.Close(True)
Set WBK = Nothing
Next i
XL.Quit
Set XL = Nothing
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.