worksheet.activate isn't activating - excel

The code snippet below is intended to open a specific worksheet of a specific XL file and make it the active worksheet. However, the debug.print gives an output of different sheets. Shouldn't objws.activate make objws the active worksheet?
Dim XLApp As New Excel.Application
Dim ObjXL As Excel.Workbook
Dim ObjWS As Excel.Worksheet
Set ObjXL = XLApp.Workbooks.Open(TargetXL)
Set ObjWS = ObjXL.Worksheets(TargetWS)
ObjWS.Activate
Debug.Print ObjWS.Application.ActiveSheet.Name & "," & ObjWS.Name

Your debug line is printing the name of the active sheet of the application, which may be a sheet in a workbook other than the workbook you have just opened. If you activate that workbook first, then the application's active sheet should become the sheet in that workbook.
I.e.
Dim XLApp As New Excel.Application
Dim ObjXL As Excel.Workbook
Dim ObjWS As Excel.Worksheet
Set ObjXL = XLApp.Workbooks.Open(TargetXL)
Set ObjWS = ObjXL.Worksheets(TargetWS)
ObjXL.Activate ' add this line
ObjWS.Activate
Debug.Print ObjWS.Application.ActiveSheet.Name & "," & ObjWS.Name
You may also want consider whether you really need to activate the worksheet. If the user specifically needs to be viewing the sheet after your VBA has run, then this is a valid reason. If however, you only need to act on the sheet in your code, then you can just reference all it's properties by using the ObjWS variable without actually activating it.

Try Select() instead.

Related

Activating opened Excel workbook from Outlook

I have a macro in my Outlook that whenever I receive an e-mail with a certain subject, it automatically opens an Excel workbook and pastes a portion of the e-mail subject in a specific cell in one of the worksheets. It works perfectly. Now I need to do this exact same process but pasting this information in an already opened workbook, instead of opening a closed file.
I've tried different solutions from my limited Excel VBA knowledge (ActiveWorkbook, worbooks(filename).activate, etc.) but none of that worked and I have not found anything similar online, as most macros are written as being run from an Excel file and not Outlook.
This is part of our current code, that opens the file and pastes the e-mail subject (which is the "ticker" value) in a specific cell on the "Lista Empresas" worksheet. What I need is a code that does the same, but in an workbook that is already opened (let's call it "test1").
Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate
There are a few scenarios to handle here. First, is Excel running? If no, then do what you are doing already. If yes - is the correct workbook open? If yes - return it, otherwise open it.
Dim ExWbk2 As Workbook
Dim wb As Workbook
Dim exapp As Excel.Application
On Error Resume Next
Set exapp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set exapp = Nothing
End If
On Error GoTo 0
If exapp Is Nothing Then
' Excel is not running
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
ExWbk2.Visible = True
Else
' Excel is running, but is the right book open?
For Each wb In exapp.Workbooks
Debug.Print wb.Name ' <-- This will help you find what to look for
If wb.Name = "ListaEmpresas_ajustado" Then
' Yes, it is!
Set ExWbk2 = wb
End If
Next
If ExWbk2 Is Nothing Then
' No, it wasn't
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
End If
End If
The trick to find out if Excel is running is GetObject. It will fail if it can't find it.
The for loop is there to allow for finding the correct workbook, based on the name. Adjust as needed.
The following code gets the object if you know the name of the sheet currently active in Excel instance. I guess this could be got from the application title using the first bit of code.
Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = GetObject("ListaEmpresas_ajustado.xlsm").Application
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate

Access to the data of a workbook in another repertory

I want to get the access of the data in a workbook in another repertory but I don't know the syntax, can you help me please ?
I have tried something like that but it doesn't work
Workbooks("U:\a.xlsx").Sheets("a").Range("A2")
To read a value you need to open that file first.
Dim MyWb As Workbook
Set MyWb = Workbooks.Open(Filename:="U:\a.xlsx", ReadOnly:=True) 'readonly if you only need to read
'read the value
Debug.Print MyWb.Worksheets("a").Range("A2")
'close it after reading
MyWb.Close SaveChanges:=False
Or if you want to do it hidden in the background without showing the workbook:
'open a new hidden Excel
Dim ExApp As Excel.Application
Set ExApp = New Excel.Application
ExApp.Visible = False
'open the workbook in that hidden ExApp
Dim MyWb As Workbook
Set MyWb = ExApp.Workbooks.Open(Filename:="U:\a.xlsx", ReadOnly:=True)
'read the value
Debug.Print MyWb.Worksheets("a").Range("A2")
'close it after reading
MyWb.Close SaveChanges:=False
'close hidden Excel
ExApp.Quit
Here a proper error handling might be useful to ensure the ExApp is closed in case of any error. Otherwise the process will stay open.
You'll need to open the workbook to access it.
Like:
Dim otherwb as Workbook
Set otherwb = Workbooks.Open("U:\a.xlsx")
Dim otherwbRange as Range
Set otherwbRange = otherwb.Sheets("a").Range("A2")
You need to create an Object for the workbook first.
Try something like:
Dim excel_wb2 As Excel.Workbook
Set excel_wb2 = Excel.Workbooks.Open("U:\a.xlsx")
x = excel_wb2.Sheets("a").Range("A2")

Access/Excel VBA Failing

I have an Access database that runs a macro that opens some Excel files and formats the sheets to prepare them for later use. This code has been running fine until my company applied the latest Office Updates, and now I am getting a compile error "Method or data member not found" and its happening on the line...
wDate = Mid(XlSheet.Range("B4").Value, 13, Len(XlSheet.Range("B4").Value))
singling out the "Range". I cannot figure out why this started happening. Thanks for any assistance. Full code below...
Function ExcelProcess()
'Variables to refer to Excel and Objects
Dim MySheetPath As String
Dim Xl As Excel.Application
Dim XlBook As Excel.Workbook
Dim XlSheet As Excel.Worksheet
Dim MyFile As Variant
Dim MySheet As Variant
Dim wBook As Variant
Dim wSheet As Variant
Dim wDate As Variant
Dim rng As Range
Dim cel As Range
MyFile = Array("w1.xlsx", "w2.xlsx", "w3.xlsx")
MySheet = Array("T2_IND", "APPR_IND", "SLG_APPR_IND", "SLG_IND", "C2A_IND", "C3_IND", "C4_IND", "T3_IND", "T4_IND", "C2B_IND")
For Each wBook In MyFile
' Tell it location of actual Excel file
MySheetPath = "\\fs1\Training\CSC_Training_Ops\Training Only\Buzzard\Pulled Data\" & wBook
'Open Excel and the workbook
Set XlBook = GetObject(MySheetPath)
'Make sure excel is visible on the screen
XlBook.Windows(1).Visible = True
For Each wSheet In MySheet
'Define the sheet in the Workbook as XlSheet
Set XlSheet = XlBook.Worksheets(wSheet)
wDate = Mid(XlSheet.Range("B4").Value, 13, Len(XlSheet.Range("B4").Value))
XlSheet.Range("A15").FormulaR1C1 = "WE_Date"
If XlSheet.Range("A16").Value <> "No data found" Then
Set rng = XlSheet.Range(XlSheet.Range("A16"), XlSheet.Range("A16").End(xlDown).Offset(-1))
For Each cel In rng.Cells
With cel
.FormulaR1C1 = wDate
.NumberFormat = "m/d/yyyy"
End With
Next cel
End If
XlSheet.Rows("1:14").Delete Shift:=xlUp
XlSheet.Range("A1").End(xlDown).EntireRow.Delete Shift:=xlUp
Next
XlBook.Close SaveChanges:=True
Next
'Clean up and end with worksheet visible on the screen
Set Xl = Nothing
Set XlBook = Nothing
Set XlSheet = Nothing
End Function
There isn't any apparent problems with the code itself.
Since this broke with when you updated the office, I would venture a guess that it is an issue with the reference.
Go to Tools->References->
Remove all references to Excel Object Library
Save & Close the Macro Worksheet (Shouldn't be necessary, but only takes a sec)
Re-Open
Add in reference to only the latest version of Microsoft Excel 1X.0 Object Library
If this does not solve the issue, you may have to run a repair on office
Control Panel -> Add Remove Programs
Locate Microsoft Excel (Or office suite)
Run Repair
Finally, it was suggested to try late binding. Remove the references to the Microsoft Excel Object Library and update your declarations to:
Dim Xl As Object
Dim XlBook As Object
Dim XlSheet As Object
Set Xl = CreateObject("Excel.Application")
Hope this helps!
Is it possible you got upgraded from Office 14.0 to 15.0 or 16.0? Hit Alt+F11 > Tools References and look for errors in the window that opens. Search for the correct reference and click it. As others have suggested, consider rewriting the code using some late binding methodologies.

Using xlpastevalues in Access VBA

I am working in Access and need to pull data from an Excel file. The file is very large with several sheets that I don't need, so I want to take the values from one sheet and put them in a new workbook in order to simplify/speed up later calculations. Currently, it is including formatting along with the values and some of my later macros are not working even though they worked when I manually pasted the values into the new sheet. I tried running this directly in Excel (removing the references to the Excel.Application variable) and it worked fine. Is there something different I should be doing since this is being run in Access?
Private Sub CopyImportFile()
Dim xl As Excel.Application
Dim SourceBook As Excel.Workbook
Dim SourceSheet As Excel.Worksheet
Dim ImportBook As Excel.Workbook
Dim ImportSheet As Excel.Worksheet
Dim SourceSheetPath As String
SourceSheetPath = "File Path"
Set xl = CreateObject("Excel.Application")
Set SourceBook = GetObject(SourceSheetPath)
Set SourceSheet = SourceBook.Worksheets("Data Tape")
Set ImportBook = xl.Workbooks.Add()
SourceSheet.UsedRange.Copy
ImportBook.Sheets(1).Cells(1,1).PasteSpecial Paste:=xlPasteValues
xl.ActiveWorkbook.SaveAs FileName:="New File Path"
SourceBook.Close False
ImportBook.Close
Set xl = Nothing
Set ImportBook = Nothing
Set SourceBook = Nothing
Set ImportSheet = Nothing

VBA - Run Macro from Word to paste values into Excel

I am relatively new to VBA, and am at a loss as to why I cannot paste into Excel from Word. The following macro ends up pasting the value into Word, even though I think I'm activating the Excel document.
The macro is meant to be run from Word; values from various FormFields then need to be pasted into cells in an existing Excel file.
I searched for a similar issue, though what was returned seemed to be variations of what I am experiencing, and I could not modify those answers to this.
Any help would be appreciated.
Sub Transfer()
Dim WD As Object
Dim ED As Excel.Application
Dim EDS As Excel.Workbook
Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
Workbooks.Open FileName:= _
"C:\Users\Documents\AppealData.xlsx"
ActiveWorkbook.Activate
Set EDS = ActiveWorkbook
WD.FormFields("AppNum").Copy
EDS.Activate
EDS.Sheets("Sheet1").Range("A1").Select
Selection.Paste
End Sub
Your Selection is referring to the current application. To refer to the Excel application you need to use ED.Selection. But it is a bad idea to rely on Activate and Select anyway.
I suggest you change your code to:
Sub Transfer()
Dim WD As Document
Dim ED As Excel.Application
Dim EDS As Excel.Workbook
Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
'Avoid "Activate"
Set EDS = ED.Workbooks.Open(FileName:= _
"C:\Users\Documents\AppealData.xlsx")
WD.FormFields("AppNum").Copy
'Avoid "Activate" and "Select" and "Selection"
'"Paste" is a worksheet Method, use "PasteSpecial" for a Range
'Use "xlPasteValues" to avoid formatting issues
EDS.Sheets("Sheet1").Range("A1").PasteSpecial Excel.xlPasteValues
End Sub
This here should work for you.
Sub Transfer()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("C:\Users\Documents\AppealData.xlsx")
oExcel.Visible = True
Workbooks("Book1").Worksheets("Sheet1").Cells(1, 1).Value = _
CStr(Documents("Document1").FormFields("AppNum").Result)
End Sub

Resources