I have a PowerPoint presentation that is has data links to an Excel file,
I am attempting to create an endless PowerPoint loop that every slide change runs a macro. This macro needs to connect to the Excel file, and if cell B2 > 0 output an action that causes an animation on the screen.
I have attempted to make PowerPoint open the Excel file but I have not been able to get further than this.
Private Sub OnSlideShowPageChange()
Dim i As Integer
Dim xlApp As Excel.Application
Dim xlWorkBook As Object
Dim Test As Object
'i = ActivePresentation.SlideShowWindow.View.CurrentShowPosition
'If i <> i Then Exit Sub
Test = 0
Set xlApp = New Excel.Application
Set xlWorkBook = xlApp.Workbooks.Open("C:\Users\Michael\Documents\Wallboard Test Data.xlsx", True, False)
Set Test = xlWorkBook.sheets("Hall of Fame").Select.Range("B2").Value
MsgBox Test
End Sub
Siddharth Rout "Remove .value as Test is an object and then use Msgbox Test.Value . Now you can use Val(Test.Value)>0 for the condition"
Related
I am working on AutoCAD plugin. Trying to implement function where it first looks for already running EXCEL instances so I just Add new workbook to existing instance instead of always creating new process.
My code fails at the point where it tries to find running process. For some reason it always detects running EXCEL process, I checked it at task manager, it is not there so that's why my plugin crashes at Marchal.GetActiveObject method because it's trying to get that running process...
My functions' code so far:
Private Function GetExcelWorksheet() As Excel.Worksheet
Dim excel As Excel.Application
Dim activeWorksheet As Excel.Worksheet = Nothing
Dim wb As Excel.Workbook = Nothing
Dim ws As Excel.Worksheet = Nothing
Dim ExcelInstances As Process() = Process.GetProcessesByName("EXCEL")
If ExcelInstances.Count() = 0 Then
Exit Function
End If
excel = TryCast(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
If excel Is Nothing Then Exit Function
excel.Visible = True
wb = excel.Workbooks.Add
ws = wb.Worksheets(1)
Return ws
End Function
'Excel.vb
Imports System
Imports System.Runtime.InteropServices
Public Module AnythingYouWantToCallIt
Sub Main
Dim Excel as Object
Dim wb as Object
Dim WS as Object
On Error Resume Next
Excel = GetObject(, "Excel.Application")
If Err.number = 429 then
Msgbox("No Excel running")
err.clear
Excel = CreateObject("Excel.Application")
If err.number = 429 then
MsgBox("Excel Not Installed")
err.clear
Else
MsgBox("New Excel has started")
End If
Else
Msgbox("Existing Excel connected to")
End If
WB = Excel.Workbooks.Add
WS = wb.Worksheets(1)
MsgBox(ws.name)
'If in a function
'Main = WS
End Sub
End Module
This does the BASIC way.
To compile above file paste following lines into a batch file and name above file excel.vb. Put the bat file in same folder as excel.vb and double click batch file.
REM Excel.bat
REM This file compiles Excel.vb to Excel.exe
REM To use
REM Excel
Rem Example
Rem
Rem Excel
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:winexe /out:"%~dp0\Excel.exe" "%~dp0\Excel.vb"
pause
Does not require Visual Studio
One would only add a Workbook, if a Workbook wasn't already open. Try the following (comments are throughout the code):
Create a new project Windows Forms App (.NET Framework)
Add Reference:
VS 2022:
In VS menu, click Project
Select Add Reference...
Click COM
Check Microsoft Excel xx.x Object Library (ex: Microsoft Excel 16.0 Object Library)
Click OK
Add the following Imports
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
GetExcelWorksheet:
Private Function GetExcelWorksheet() As Excel.Worksheet
Dim excel As Excel.Application
Dim activeWorksheet As Excel.Worksheet = Nothing
Dim wb As Excel.Workbook = Nothing
Dim ws As Excel.Worksheet = Nothing
'get existing Excel processes
Dim ExcelInstances As Process() = Process.GetProcessesByName("EXCEL")
For Each instance In ExcelInstances
Debug.WriteLine($"ExcelInstances: ProcessName: {instance.ProcessName} Id: {instance.Id}")
Next
If ExcelInstances.Count() = 0 Then
Debug.WriteLine("No Excel instances found")
Exit Function
End If
Debug.WriteLine("Getting Active Excel instance...")
excel = TryCast(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
If excel Is Nothing Then Exit Function
Debug.WriteLine("Setting Excel visible")
'ensure Excel is visible
excel.Visible = True
'get active workbook
wb = excel.ActiveWorkbook
If wb Is Nothing Then
Debug.WriteLine("Adding Workbook...")
wb = excel.Workbooks.Add()
End If
Debug.WriteLine($"wb.Sheets.Count: {wb.Sheets.Count}")
'set worksheet
ws = DirectCast(wb.Sheets(1), Excel.Worksheet)
'activate worksheet
ws.Activate()
'add new Worksheet
ws = DirectCast(wb.Sheets.Add(After:=wb.Sheets(1)), Excel.Worksheet)
ws.Name = "My Worksheet Name" 'set worksheet name
Debug.WriteLine($"wb.Sheets.Count: {wb.Sheets.Count}")
'set value - for A1 also known as 1,1
ws.Cells(1, 1) = $"{DateTime.Now.ToString("HH:mm:ss.fff")}"
Return ws
End Function
Here are some additional methods that may be useful:
Note: If your application has open resources to Excel, Excel may still be running even after clicking the X(in the upper-right corner) of the Excel window. If one opens Task Manager, Microsoft Excel can be seen under "Background processes". To quit Excel, see the code below.
Public Function IsExcelRunning() As Boolean
'get existing Excel processes
Dim ExcelInstances As Process() = Process.GetProcessesByName("EXCEL")
For Each instance In ExcelInstances
Debug.WriteLine($"ExcelInstances: ProcessName: {instance.ProcessName} Id: {instance.Id}")
Next
If ExcelInstances.Count() = 0 Then
Debug.WriteLine($"IsExcelRunning: False")
Return False
End If
Debug.WriteLine($"IsExcelRunning: True")
Return True
End Function
Public Function IsExcelVisible() As Boolean
Dim excel As Excel.Application
'get existing Excel processes
Dim ExcelInstances As Process() = Process.GetProcessesByName("EXCEL")
For Each instance In ExcelInstances
Debug.WriteLine($"ExcelInstances: ProcessName: {instance.ProcessName} Id: {instance.Id}")
Next
If ExcelInstances.Count() = 0 Then
Debug.WriteLine("No Excel instances found")
Exit Function
End If
Debug.WriteLine("Getting Active Excel instance...")
excel = TryCast(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
If excel Is Nothing Then Return False
Debug.WriteLine($"IsExcelVisible: {excel.Visible}")
Return excel.Visible
End Function
Public Sub QuitExcel()
Dim excel As Excel.Application
Dim wb As Excel.Workbook = Nothing
Dim ws As Excel.Worksheet = Nothing
'get existing Excel processes
Dim ExcelInstances As Process() = Process.GetProcessesByName("EXCEL")
For Each instance In ExcelInstances
Debug.WriteLine($"ExcelInstances: ProcessName: {instance.ProcessName} Id: {instance.Id}")
Next
If ExcelInstances.Count() = 0 Then
Debug.WriteLine("No Excel instances found")
Exit Sub
End If
Debug.WriteLine("Getting Active Excel instance...")
excel = TryCast(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
If excel Is Nothing Then Exit Sub
wb = excel.ActiveWorkbook
If wb IsNot Nothing Then
Debug.WriteLine($"Closing Excel Workbook...")
wb.Close(False)
'release resources
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wb)
End If
Debug.WriteLine($"Quiting Excel.")
'quit Excel
excel.Quit()
'release resources
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excel)
GC.Collect() 'force garbage collection
End Sub
Resources
Microsoft.Office.Interop.Excel
How do you list all processes on the command line in Windows?
C# Close Excel Instance opened by another application
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
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
I'm attempting to copy the contents of a text box from one workbook to another. I have no problem copying cell values from the first workbook to the 2nd, but I get an object required error when I attempt to copy the text box. This macro is being run from the workbook containing the data I want copied. Using Excel 2007 Code:
Sub UploadData()
Dim xlo As New Excel.Application
Dim xlw As New Excel.Workbook
Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
xlo.Worksheets(1).Cells(2, 1) = Range("d4").Value 'Copy cell content (this works fine)
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text 'This gives me the object required error
xlw.Save
xlw.Close
Set xlo = Nothing
Set xlw = Nothing
End Sub
Thanks for any help.
The problem with your macro is that once you have opened your destination Workbook (xlw in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.
Sub UploadData()
Dim xlo As New Excel.Application
Dim xlw As New Excel.Workbook
Dim myWb as Excel.Workbook
Set myWb = ActiveWorkbook
Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text
xlw.Save
xlw.Close
Set xlo = Nothing
Set xlw = Nothing
End Sub
If you prefer, you could also use myWb.Activate to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).
I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".
EDIT
It looks like you may be able to use the GetObject function to pull the textbox from the workbook.
The issue is with this line
xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text
You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.
Hence replace this with
xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text
I have a powerpoint pres that grabs some data from an excel sheet when a button is pressed.
Set EXL = New Excel.Application
EXL.Visible = False
Dim XLApp As Excel.Application
Set XLApp = GetObject(, "Excel.Application")
This is how I set the new excel application.
What I'm wondering is how I can send over a variable from my powerpoint slide into the excel workbook? I have textfield in my powerpoint slide that I want the text to be used in a variable inside excel. Is this possible? If so, how?
And how do I, from a powerpoint module, call a Sub within the excel workbook to run?
(This is some simplified production code from an Access db, powerpoint might have a few minor differences)
What I'm wondering is how I can send over a variable from my powerpoint slide into the excel workbook?
Sub SetXLCellValue( _
FileStr As String, _
TabStr As String, _
Cell As String)
Dim XLApp As New Excel.Application
Dim ObjXL As Excel.Workbook
Set ObjXL = XLApp.Workbooks.Open(FileStr)
ObjXL.Worksheets(TabStr).Range(Cell).value = value
ObjXL.Save
ObjXL.Close True
End Sub
As for calling a Sub in your Excel application, you can use
XLApp.Run("MySub")
This also has the ability to pass parameters to the method (intellisense should show you the way)