How to select/activate a worksheet from word-VBA? - excel

I use two screen monitors. The left monitor has an Excel Workbook opened. The right monitor has a Microsoft Word document opened. I use a Word Userform to bring data from the opened workbook to the opened Word document.
But sometimes I need to change the activated/selected worksheet (I mean, the one that is in front of the others; th3e one I can see), and I would like to do so from a button in my Microsoft Word userform.
The code below does not work, and I have no idea how to achieve that goal.
Please, would someone have an idea how to achieve that?
Sub ACTIVATE_WORKSHEET_ASDF()
Dim MyExcel As Excel.Application
Dim MyWB As Excel.Workbook
Set MyExcel = New Excel.Application
Set MyWB = MyExcel.Workbooks.Open("MY EXCEL WORKBOOK FULL PATH")
Dim ASDF As Worksheet
Set ASDF = MyWB.Sheets("ASDF")
ASDF.Select 'DO NOT WORK
ASDF.Activate 'DO NOT WORK
Debug.Print ASDF.Cells(1,1) 'DOES WORK!
MyWB.Close False
Set MyExcel = Nothing
Set MyWB = Nothing
End Sub

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")

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

Populate Word Combobox with Excel data through VBA

I'm new to VBA, so I'm struggling with this for a couple of days now.
I have a combobox in Word with contacts, I also have an excel file(contacts.xls) with one column (names of the all the contacts). When I open the Word-document the Macro has to fill in the combobox with all the names from the excel file.
Is it possible to send me a working example of this for word 2007? Seems quite simple, but just can't get this to work...
Thanks in advance!
If you intend on reading from an Excel file in Word you are going to have to open it. It will use code like this:
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open("FileName.xlsx")
You will also probably want to go to Tools->References in the VB project and find whatever Excel library is on your machine (and check it of course). There are ways around this if needed, but it is easier.
You then can read the values from the workbook:
oBook.Worksheets(1).cells(1,1)
I'm not totally sure what the syntax to get it into the combo box is. Look up "combobox object members" in the vbe in word. There will be a list property, or something like that.
Sorry, I'm on a linux machine right now, so I can't debug exact code for you.
I have more full code for you now:
Option Explicit
Sub TestDropDownFromExcel()
Dim counter As Long
Dim xlApp As Excel.Application
Dim xlBook As Workbook
Dim oCC As ContentControl
Set oCC = ActiveDocument.ContentControls(1)
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Path\To\MyFile.xlsx")
If xlBook Is Nothing Then
Exit Sub
End If
oCC.DropdownListEntries.Clear
For counter = 1 To 10
oCC.DropdownListEntries.Add Text:=xlBook.Worksheets(1).Cells(counter, 1), Value:=CStr(counter)
Next counter
xlApp.Visible = True
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
Be aware that there is very little error checking going on here. Also, rather than the call to .Visible at the end, you can simply call .Close if you do not want the user to see it (for the final project, this is probably preferable. The deferencing (= Nothing) is good practice to have, but VBA cleans up automatically at the end of execution. Obviously I am assuming tyou want the first dropdown (ContentCOntrols(1)) but this may not be true.

worksheet.activate isn't activating

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.

Resources