Copying a Chart in VBA after Opening Excel File - vba

I have a VBA Module in Word2007 with a main sub which calls an OpenExcelFile sub to open an Excel Workbook. It opens successfully, but then in my main sub, I am having trouble selecting and copying a particular chart. I want to then paste the chart into word as a picture.
Const Fuelpath As String = "\\PATH\Fuel_Price_Screen.xls"
Sub Main()
OpenExcelFile (Fuelpath)
'''This is where I would like to Copy the only Chart on the first Excel Sheet (named "$$Screen,"
'''but I keep getting errors. I would like to paste it into the Word doc called
'''"daily summary automation," which the VBA module is running in.
End Sub
Sub OpenExcelFile(ByVal Filepath As String)
Dim xlApp As Object
xlApp.Application.Visible = True
xlApp.Workbooks.Open (Fuelpath)
End Sub

Related

Excel VBA - How to use worksheet event in add-in module?

I am new to Excel Add-ins and I am not sure how to write mi programm.
I would like to put in an add-in a code so that, when the workbook that uses the add-in is opened, it creates a sheet named "mainSheet".
I can use the event handler in the Workbook, but is it possible to put the code in the module of the add-in and still be able to run it?
I found this on the "Automate Excel" web site. Hope this helps
The following code works opening a workbook. It automatically adds a new sheet and labels it with the name. It also checks to see that the sheet doesn’t already exist – to allow for the possibility of it being opened more than once a day.
This code makes use of the Workbook Open Event and must be placed in the workbook module under the “Open work Book” event. The function Sheet_Exists must be placed in a module and this checks whether or not the sheet exists:
Private Sub Workbook_Open()
Dim New_Sheet_Name As String
New_Sheet_Name = "mainSheet"
If Sheet_Exists(New_Sheet_Name) = False Then
With Workbook
Worksheets.Add().Name = New_Sheet_Name
End With
End If
End Sub
==
Function Sheet_Exists(WorkSheet_Name As String) As Boolean
Dim Work_sheet As Worksheet
Sheet_Exists = False
For Each Work_sheet In ThisWorkbook.Worksheets
If Work_sheet.Name = WorkSheet_Name Then
Sheet_Exists = True
End If
Next
End Function

How to hide sheets in your excel file that are not filled in

I have an excel that hides certain sheets when opening the document. So like
Private Sub Workbook_Open()
Worksheets("screen_2").Visible = xlHidden
Worksheets("screen_3").Visible = xlHidden
end sub
Now I have the case that someone fills in either sheet "screen_2" or "screen_3". Right now when someone has filled in either screen_2 of screen_3 sheet closes the document and reopen the excel sheet "screen_2" and "screen_3" are not visible.
What I would like to achieve is that the first time you open the excel document both sheets should be hidden but that when you fill in one of the two sheets that particular sheet should not be hidden when reopening the excel file.
So when I open the excel sheet and fill in screen_2, save, close en reopen the file "screen_2" sheet should be visible (and screen_3 hidden) and when I open the excel doc and fill in screen_3, save, close en reopen the file "screen_3" sheet should be visible (and screen_2 hidden)
Any thoughts on how I can get this working?
once you get through how to fill a hidden sheet, then you could use:
Private Sub Workbook_Open()
CheckIfHideSheet Worksheets("screen_2")
CheckIfHideSheet Worksheets("screen_3")
End Sub
Sub CheckIfHideSheet(sht As Worksheet)
With sht
If .UsedRange.Address = "$A$1" And IsEmpty(.Cells(1, 1)) Then .Visible = xlHidden
End With
End Sub

Input Box on workbook open

I am trying to come up with some vba code to open an input box automatically as soon as the workbook is opened and have the user enter a date and then have the date placed in the A1 cell. I have written the code below but the input box is not pulling up at all it just opens the workbook and moves on.. not sure what is happening. Any and all help is appreciated.
Thanks!
Option Explicit
Private Sub workbook_open()
Dim cellvalue As Variant
Dim ws As Worksheet
Set ws = Worksheets("Workbench Report")
ReShowInputBox: cellvalue = Application.InputBox("Please Enter Todays Date (dd/mm/yyyy)")
If cellvalue = False Then Exit Sub
If IsDate(cellvalue) And CDate(cellvalue) < Date Then
ws.Range("A1").Value = DateValue(cellvalue)
Else: MsgBox ("Invalid Date!")
GoTo ReShowInputBox
End If
End Sub
Your code triggers upon the Workbook opening for me. Try these steps.
Open up Excel and Save As, changing the extension to .XSLM
Open up the VBA Editor (ALT + F11)
In the left-hand window, locate your macro file (the one you just created and named - it's in brackets after "VBA Project"), drilldown to "This Workbook" and double-click it.
Paste your code into the right-hand window
Save the file and re-open.
See attached diagram.
By the way, "cellValue = false" should probably be cellValue = "" since InputBox is returning a string and not a boolean value.
For Workbook_Open events the script needs to reside in the private module (ThisWorkbook)
From Ozgrid:
the Workbook_Open event is a procedure of the Workbook Object and as
such, the Workbook_Open procedure MUST reside in the private module of
the Workbook Object (ThisWorkbook).

Excel VBA Can't access sheet on external workbook

I have created a custom function in Excel using VBA. I'm trying to get data from a different workbook using the Workbooks.Open(path) command. Here's my code:
Option Explicit
Function TestFunction() As String
mySub
TestFunction = "Success."
End Function
Sub mySub()
Dim path As String
Dim wk As Workbook
path = "C:\Users\jg\Desktop\machine_data.xlsm"
Set wk = Workbooks.Open(path)
Dim ws As Worksheet
Set ws = wk.Sheets(1)
Debug.Print ws.Range("A2")
End Sub
Sub Test()
Debug.Print (TestFunction())
End Sub
Now my problem is the following:
When I run the Sub Test() within the VBA environment from Excel everything works as planned. machine_data.xlsm gets opened and the field A2 shows up in debug.
Once I go to the workbook where I defined this module in and type =TestFunction() into a cell, I get a #VALUE!. The file also doesn't get opened.
If I comment these two lines:
Set ws = wk.Sheets(1)
Debug.Print ws.Range("A2")
the cell will show Success!, but the file still doesn't open.
What am I doing wrong? Both workbooks are .xlsm files. I am using Microsoft Office Excel 2007.
Just throw everything from mySub into the test function and if everything is successful have test function return the value of the cell. So testFunc = ws.Range("A2").
As DaveU already stated UDFs can only return values. I found a different workaround simply calling the function from within the VBA environment which lets me modify cell contents wherever I'd like.

Deactivating OLEObject with VBA breaks ribbon in Word 2007

I am writing a script that loops through the embedded excel sheets in my document with VBA. I activate them, do some modifications and go on with the next one. Afterwards, I want the last sheet to be deactivated again and I want the cursor to return to the start of the document.
I have the following code so far:
Private Sub DeactivateOleObject(ByRef oOleFormat As OLEFormat)
On Error Resume Next
oOleFormat.ActivateAs "This.Class.Does.Not.Exist"
End Sub
Sub AutoOpen()
Dim lNumShapes As Long
Dim lShapeCnt As Long
Dim xlApp As Object
Dim wrdActDoc As Document
Set wrdActDoc = ActiveDocument
For lShapeCnt = 1 To wrdActDoc.InlineShapes.Count
If wrdActDoc.InlineShapes(lShapeCnt).Type = wdInlineShapeEmbeddedOLEObject Then
Dim oOleFormat As OLEFormat
Set oOleFormat = wrdActDoc.InlineShapes(lShapeCnt).OLEFormat
oOleFormat.Activate
DeactivateOleObject oOleFormat
End If
Next lShapeCnt
End Sub
I borrowed the deactivation code from Gary McGill. However, this method of deactivation breaks the ribbon in Word 2007.
I can imagine that it would be nicer to reactivate the main document instead of deactivating the OLEObject, but adding wrdActDoc.Activate doesn't seem to do this.
Is it possible to deactivate the excel worksheet without breaking the ribbon?
I don't agree with "tricking" Word like that with Gary's code you reference. See my other post on Update embedded excel file programmatically for how to safely deactivate (but know that it is SendKeys, so it will never be 100% perfect).