VBA: Activate method not found - vba

I have some VBA code that was working perfectly a few weeks ago, but now is crashing with an error. The code, which is triggered from Word, is meant to open an Excel file. The specific error I'm getting is related to the Activate method.
Sub Populate()
Dim eApp As Excel.Application
Dim eWB As Excel.Workbook
Dim eSheet As Excel.Worksheet
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = New Excel.Application
End If
'Open Workbook
WorkbookName = "(Excel file location)"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
(etc.)
I'm a VBA novice so I'm sure there's a better way to write the above. It's the final line - eWB.Activate - that creates a compile error, "Method or data member not found." Again, this was working last month and isn't working now. Has something changed in Office 2016 that makes this code illegal?
I played around and think I have a workaround, but I'd still like to know why this is crashing, for future reference. Thanks.
EDIT: Here is the error

Do not know why you have that Error when you have On Error Resume Next from there on. Are there codes missing from what you have posted? Also is the Excel workbook macro enabled that may interfere the codes in Word?
You may also try Late Binding for those Excel Objects once you are done coding with IntelliSense. Just to demonstrate how I would code this Excel file open part (Excel 2010):
Option Explicit
Sub Populate()
Dim eApp As Object ' Excel.Application
Dim eWB As Object ' Excel.Workbook
Dim eSheet As Object ' Excel.Worksheet
Dim ExcelWasNotRunning As Boolean
Dim WorkbookName As String
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If eApp Is Nothing Then Set eApp = CreateObject("Excel.Application")
ExcelWasNotRunning = eApp Is Nothing
If ExcelWasNotRunning Then Exit Sub
'Open Workbook
WorkbookName = "C:\Test\Tables.xlsx"
eApp.Visible = True
'eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
On Error GoTo 0 ' Turns on Debug prompt on Error
If Not eWB Is Nothing Then
With eWB
.Activate
' process stuff
.Save
.Close
End With
Set eWB = Nothing
End If
eApp.Quit
Set eApp = Nothing
End Sub

I ran this from word and it worked, I think somehow you have an early binding problem, which is most likely is due to installing a new version of word on your machine. You can google it and clean your registry to get rid of it.
Sub Populate()
Dim eApp As Object
Dim eWB As Object
Dim eSheet As Object
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = CreateObject("Excel.Application")
End If
'Open Workbook
WorkbookName = "\\grid\sasprod\ci\reports\Quickmarks\Quickmarks Tables A.xlsx"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
End Sub

Related

Window not visible despite running in background

I have a macro that I'm trying to run through Access that will open up an excel sheet, do some actions on it, and then leave the sheet open.
I have most of it working, with the exception of not being able to get my excel document to open visibly. If I check the task manager, an excel process is running in the background so something does happen, just nothing that I can physically see.
I've attempted to sample some code found through stackoverflow and other resources, which I'm sure you'll see some of that in my current code. But I tried for about an hour with no avail.
Private Sub Command1_Click()
Dim fd As FileDialog
Dim MySheetPath As String
Dim Xl As Excel.Application
Dim XlBook As Excel.Workbook
Dim XlSheet As Excel.Worksheet
On Error GoTo ErrorHandler
'allowing selection of the time
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
If fd.Show = True Then
If fd.SelectedItems(1) <> vbNullString Then
MySheetPath = fd.SelectedItems(1)
End If
Else
End
End If
Set Xl = CreateObject("Excel.Application")
Set XlBook = GetObject(MySheetPath)
ShowaWindow (MySheetPath)
Set XlSheet = XlBook.Worksheets(1)
XlSheet.Rows(2).EntireRow.Insert
XlSheet.Range("D2") = "ABC"
Set Xl = Nothing
Set XlBook = Nothing
Set XlSheet = Nothing
Exit Sub
ErrorHandler:
Set fd = Nothing
MsgBox "Error " & Err & ": " & Error(Err)
End Sub
Sub ShowaWindow(sFileName As String)
Dim oWb As Workbook
Set oWb = GetObject(sFileName)
For Each oWb In Workbooks
If LCase(oWb.Name) <> LCase(sFileName) Then
oWb.Windows(1).Visible = True
Exit For
End If
Next
End Sub
Ideally I would like to be able to see the worksheet appear.
Set Xl = CreateObject("Excel.Application")
Xl.Visible=True
You don't need to put it immediately after creating the object, just before you set the object to Nothing.
Set XlBook = GetObject(MySheetPath)
This is wrong. Don't use GetObject to open the workbook, use the Excel.Application instance you just created:
Set XlBook = Xl.Workbooks.Open(MySheetPath)
Later you iterate all opened workbooks:
For Each oWb In Workbooks
But that's not the Workbooks collection from the Xl application instance, it's the Workbooks collection from the instance that's currently running your code - you need to qualify it with the Xl object:
Private Sub ShowaWindow(ByVal app As Excel.Application, ByVal sFileName As String)
'...
For Each oWb In app.Workbooks
Also, make the app instance visible after you created it, and don't forget to invoke XlBook.Close and Xl.Quit to properly tear down that EXCEL.EXE process when you're done.

Error: "Method 'rows' of object '_Global' failed

For some reason even though I am referring to the oSheet variable it is returning the error as if I am referring to a global variable?
PS I am trying to populate a combobox in word with a contractor names from an excel sheet I have created. I searched in google and here, none of the solutions have worked for me unfortunately. I believe the error lies within the For Each statement.
Sub Macro3()
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String
'specify the workbook to work on
WorkbookToWorkOn = "C:\Users\Nathan\Desktop\KTC\VBA Experiment\Excel Files\testExcel.xlsx"
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application
End If
On Error GoTo Err_Handler
'If you want Excel to be visible, you could add the line: oXL.Visible = True here; but your code will run faster if you don't make it visible
'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)
'Process each of the spreadsheets in the workbook
For Each oSheet In oXL.ActiveWorkbook.Worksheets
'put guts of your code here
'get next sheet
If oSheet.Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
lastRow = 2
Else
lastRow = oSheet.Cells(Rows.Count, 1).End(xlUp).Row
End If
' For i = 2 To lastRow
' workZonerForm.contracterCMB.AddItem oSheet.Cells(i, 1)
' Next i
MsgBox lastRow
Next oSheet
If ExcelWasNotRunning Then
oXL.Quit
End If
'Make sure you release object references.
Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing
'quit
Exit Sub
Err_Handler:
MsgBox WorkbookToWorkOn & " caused a problem. " & Err.Description, vbCritical, _
"Error: " & Err.Number
If ExcelWasNotRunning Then
oXL.Quit
End If
End Sub

copying active sheet into another workbook: Copy Method of Range class failed

I want my code to copy the entire worksheet(SOURCE) and paste it into some other worksheet(TARGET) under other workbook(WHERE_I_WANNA_PASTE_IT) and save it.
I am getting this error:
Run=-time error '1004': Copy Method of Range class failed
on this line:
CurrentSheet.Cells.Copy Destination:=oSheet.cells
The code:
Public Const path1 As String = "C:\Where_I_WANNA_PASTE_IT.xlsb"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim CurrentSheet As Object
Sub copyNpaste
Set CurrentSheet = ActiveSheet
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(path1)
Set oSheet = oBook.Worksheets("TARGET")
'Deleting what's on "TARGET" first
oSheet.cells.delete
'This is where the Error happens.
CurrentSheet.Cells.Copy _
Destination:=oSheet.Cells
oBook.Save
oBook.Close
Set oExcel = Nothing
Set oBook = Nothing
Set oSheet = Nothing
Set CurrentSheet = Nothing
End Sub
A couple of suggestions, this should work (at least it does on my computer, I was able to perfectly replicate your bug):
FIX 1
Don't create a new Excel application, use the same thread; in other words, remove this:
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(path1)
and write this:
Set oBook = Workbooks.Open(path1)
FIX 2
You can set your active sheet when you want, but be clear with the reference, use "ThisWorkbook" so the compiler will be happy and you don't risk to reference the other sheet (this is always a good practice, never fully trust the default reference if you already know what your expected reference is, like in this case):
Set CurrentSheet = ThisWorkbook.ActiveSheet
and a SUGGESTION...
Put an error handler: if the method fails, you will find with a bunch of openend Excel threads (check it out, you will have as many as you have already failed running your code. Here is how I would write the full code (suggestion included):
Public Const path1 As String = "C:\yourfile.xlsb"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Dim CurrentSheet As Object
Sub copyNpaste()
Set oBook = Workbooks.Open(path1)
Set oSheet = oBook.Worksheets("TARGET")
Set CurrentSheet = ThisWorkbook.ActiveSheet
On Error GoTo ESCAPE 'if the code fails, we go to "Escape" and at least we close the file
'Deleting what's on "TARGET" first
oSheet.Cells.Delete
'This is where the Error happens.
CurrentSheet.Cells.Copy _
Destination:=oSheet.Cells
oBook.Save
ESCAPE:
oBook.Close
Set oExcel = Nothing
Set oBook = Nothing
Set oSheet = Nothing
Set CurrentSheet = Nothing
End Sub
NOTE
Open your Task Manager (Ctrl+Alt+Del) and go to processes... close all the EXCEL.EXE processes you have probably left everytime you have failed running your code, before your laptop explodes :)

Using Access 2010 VBA list all open Excel Workbooks

Ok, I must be missing something subtle here.
In Excel 2010 this VBA works:
Private Sub ExcelTest()
Dim wb As Workbook
For Each wb In Workbooks
Debug.Print wb.Name
Next wb
End Sub
I'm trying to replicate this in Access VBA and I've tried the following approaches in Access 2010 with no success.
Private Sub AccessTest1()
'Derived from http://stackoverflow.com/questions/15958061/controlling-excel-
'workbook-from-access-2010-vba
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Set xlApp = New Excel.Application
For Each xlWB In Excel.Workbooks
Debug.Print xlWB.Name
Next xlWB
'Nothing happens.
'Stepping through and hovering:
'xlApp = "MicroSoft Excel"
'xlWB = Nothing
'xlWB.Name = Object variable or With block variable not set.
'But doesn't throw an error.
End Sub
Private Sub AccessTest2()
'Derived from http://stackoverflow.com/questions/5729195/how-to-refer-to-excel-
'objects-in-access-vba
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Set xlApp = New Excel.Application
For Each wb In Excel.Workbooks '<--- Like this nothing happens
Debug.Print wb.Name
Next wb
'Stepping through and hovering:
'xlApp = "MicroSoft Excel"
'wb = Nothing
'wb.Name = Object variable or With block variable not set. But doesn't throw an error.
For Each wb In xlApp.Workbooks '<--- This throws a "Object variable or
'With block variable not set" error
Debug.Print wb.Name
Next wb
End Sub
Private Sub AccessTest3()
'Derived from http://stackoverflow.com/questions/5729195/how-to-refer-to-excel-
'objects-in-access-vba
Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbook '<--- Throws "Object doesn't support this property
'or method error"
'Hovering after error:
'objExcelApp = "MicroSoft Excel"
'wb = Nothing
For Each wb In objExcelApp.Workbooks
Debug.Print wb.Name
Next wb
End Sub
I definitely have the "Microsoft Excel 14.0 Object Library" reference checked in Access.
I'm just trying to list any open Excel Workbooks so that I can then act against that information.
Thanks for your help in advance.
Set xlApp = New Excel.Application creates a new instance of Excel - and of course you do not have any workbooks in there.
What you want to achive is to go thru an already opened Excel instance. Therefore you have to use getObject().
Another Error is in your For statement ... you have to use xlApp.Workbooks instead of Excel.Workbooks.
The following code should provide the exprected result:
Dim xlApp As Excel.Application
Set xlApp = GetObject(, "Excel.Application")
Dim xlWB As Excel.Workbook
For Each xlWB In xlApp.Workbooks
Debug.Print xlWB.Name
Next xlWB
Set xlApp = Nothing
Set xlWB = Nothing
Please keep also in mind to destry object variables on the end by setting them to Nothing.

VBA Type mismatch error when setting Excel Range in Word

I have the following code as part of my sub trying to assign a range:
'Set xlApp = CreateObject("Excel.Application")
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
xlApp.Visible = False
xlApp.ScreenUpdating = False
Dim CRsFile As String
Dim CRsMaxRow As Integer
' get the CR list
CRsFile = "CRs.xls"
Set CRsWB = xlApp.Workbooks.Open("C:\Docs\" + CRsFile)
With CRsWB.Worksheets("Sheet1")
.Activate
CRsMaxRow = .Range("A1").CurrentRegion.Rows.Count
Set CRs = .Range("A2:M" & CRsMaxRow)
End With
Dim interestingFiles As Range
' get the files names that we consider interesting to track
Set FilesWB = xlApp.Workbooks.Open("files.xlsx")
With FilesWB.Worksheets("files")
.Activate
Set interestingFiles = .Range("A2:E5")
End With
Do you have any idea why am I getting a run time type mismatch error?
If you run the code from Word then the problem is in the declaration of 'interestingFiles' variable. Range exist in Word as well so use either Variant or add reference to Excel and then use Excel.Range.
Without Excel reference:
Dim interestingFiles As Variant
And with Excel reference:
Dim interestingFiles As Excel.Range
Kindly set xlApp object as in below code.
Also you provide complete path for your workbook when opening it.
Sub test()
Dim interestingFiles As Range
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
' get the files names
Dim path As String
path = "C:\Users\Santosh\Desktop\file1.xlsx"
Set FilesWB = xlApp.Workbooks.Open(path)
With FilesWB.Worksheets(1)
.Activate
Set interestingFiles = .Range("A2:E5")
End With
End Sub