I have some code below, It works like a charm but I’m curious about some things.
Why can’t I make a
Set xWorkb = new Workbookstatement? Instead I use the
Dim xWorkb as new Workbook, which works. But I’ve learned (hopefully correct) that using the
newstatement within a
Dimis bad practice, and that you should create the object seperately. So why doesn’t it work? I get a ActiveX component can’t create object error, but the
xWorkbis still being created later as an object right due to the new statement in the
Dimsection? Makes me confusing.
Why can’t I use the
excel.application.workbookswhen defining variable
xApp? Is it because I have to specify a workbook and can’t just leave the workbooks empty like that? I get a type mismatch error when I’m trying to change
Sub tester() Dim xWorkb As New Workbook Dim xApp As Excel.Application: Set xApp = New Excel.Application Dim xFiles_target() As Variant Dim file_path As String xFiles_target = Array("Bella.xls", "Fizz.xls", "Milo.xls", "Jake.xls") file_path = Dir("C:\Users\hans\Desktop\") Do While Len(file_path) > 0 Debug.Print file_path If UBound(Filter(xFiles_target, file_path)) >= 0 Then Debug.Print "found " & file_path Set xWorkb = xApp.Workbooks.Open("C:\Users\hans\Desktop\" & file_path) xApp.ActiveSheet.Cells(2, 2) = "tester" xWorkb.Save xWorkb.Close End If file_path = Dir Loop End Sub
You cannot create new workbooks with
New because workbooks are coupled with
Application and must be created with
Dim xWorkb as new Workbook does not work – it appears to work because you don’t access
xWorkb between declaring it and assigning it with
Workbooks.Open. If you did, you would get the same ActiveX component can’t create object error.
The error is because
Excel.Workbook does not have any public constructors.
You cannot define a variable as
excel.application.workbooks because that is not a type. It is a property named
Workbooks, of type
Excel.Workbooks, that belongs to an object named
Application of type
You can declare the variable as
Excel.Workbooks, but you probably don’t want to, because you will need to create an
Excel.Application to use it anyway.