Home » excel » vba – Set xWorkb = New workbook not working, ActiveX error

vba – Set xWorkb = New workbook not working, ActiveX error

Posted by: admin May 14, 2020 Leave a comment

Questions:

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 Workbook statement? Instead I use the Dim xWorkb as new Workbook, which works. But I’ve learned (hopefully correct) that using the new statement within a Dim is 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 xWorkb is still being created later as an object right due to the new statement in the Dim section? Makes me confusing.

  • Why can’t I use the excel.application.workbooks when 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 excel.application to excel.application.workbooks.

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
How to&Answers:

You cannot create new workbooks with New because workbooks are coupled with Application and must be created with Workbooks.Add or Workbooks.Open.

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 Excel.Application.
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.