Excel VBA runs step by step but not in whole - excel

I have written the below code to export data from SAP GUI.
If I go step by step everything works fine. Excel is exported and data is copied to the proper place. But if I try to run it NOT step by step it goes on error (subscript out of range).
The problem is at the 'close SAP session part of the code. from that point the code does not run forward if I try to run it at once. I tried to use a timer which stops the code until the exported file opens but it does not help but I am sure that the problem is that the exported file opens too slowly and the code can't run forward.
Do you have any idea how to solve this? Thanks
Sub SapExport_Returns()
Dim wb As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim Wbname As String
'SapExport file is open with Cover sheet filled and Data sheet empty
Set wb = Workbooks("SAP export")
Set ws = wb.Worksheets("Cover")
Set ws2 = wb.Worksheets("Data")
'turn off screen update
Application.ScreenUpdating = False
If Not IsObject(SAPApplication) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApplication = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(SAPConnection) Then
Set SAPConnection = SAPApplication.Children(0)
End If
If Not IsObject(SAPsession) Then
Set SAPsession = SAPConnection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject SAPsession, "on"
WScript.ConnectObject Application, "on"
End If
'Disable the Application Alert before saving the file
Application.DisplayAlerts = False
SAPsession.findById("wnd[0]").maximize
'transaction code
SAPsession.findById("wnd[0]/usr/cntlIMAGE_CONTAINER/shellcont/shell/shellcont[0]/shell").doubleClickNode "F00006"
'company code
SAPsession.findById("wnd[0]/usr/ctxtDD_BUKRS-LOW").Text = CStr(ws.Range("C3").Value)
'open items on date
SAPsession.findById("wnd[0]/usr/ctxtPA_STIDA").Text = ws.Range("H5").Value
'layout
SAPsession.findById("wnd[0]/usr/ctxtPA_VARI").Text = CStr(ws.Range("H8").Value)
SAPsession.findById("wnd[0]/usr/ctxtPA_VARI").SetFocus
SAPsession.findById("wnd[0]/usr/ctxtPA_VARI").caretPosition = 11
SAPsession.findById("wnd[0]/tbar[1]/btn[8]").press
SAPsession.findById("wnd[0]/mbar/menu[0]/menu[3]/menu[1]").Select
'workbook naming
Wbname = CStr(ws.Range("C15").Value)
SAPsession.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = Wbname
SAPsession.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 8
SAPsession.findById("wnd[1]/tbar[0]/btn[0]").press
'close SAP session
'session.findById("wnd[0]").maximize
'session.findById("wnd[0]/tbar[0]/btn[15]").press
'session.findById("wnd[0]/tbar[0]/btn[15]").press
'Enabling the Application Alerts after saving the file
Application.DisplayAlerts = True
'wait until SAP exported file opens
newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 50
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime
'copying formatted data to file and close SAP extract
Workbooks(Wbname).Worksheets("Sheet1").Range("A1").CurrentRegion.Copy ws2.Range("A2")
ws2.Range("A2").CurrentRegion.Columns.AutoFit
ActiveWindow.DisplayGridlines = False
ws2.Name = "FBL5N"
wb.Sheets.Add.Name = "Data"
'Turn on screen update
Application.ScreenUpdating = True
End Sub

Related

Excel VBA: speed up macro which sets column width and view settings

My team and I have an excel file where I use columns A to L. We use this file to send out different budgets and therefore have multiple versions of the file. What happens is that people start to adjust the column widths and afterwards the print area no longer fits.
We want to ensure a standardized layout version at all times.
I have set up a VBA that ensures that the pre-selected column widths are implemented upon opening the file. If somebody changes the width, this will automatically be adjusted when somebody else opens the file again.
The code I have works fine however, one problem is that it takes to long to run 2min30sec. Any suggestions on how to speed it up?
Sub Workbook_Open()
'-----START TIMER-----
Dim StartTime As Double
Dim TimeTaken As String
Dim ws As Worksheet
StartTime = Timer
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.AskToUpdateLinks = True
Application.DisplayAlerts = True
Application.Calculation = xlAutomatic
ThisWorkbook.Date1904 = False
Application.StatusBar = False
On Error Resume Next
'For Each ws In ActiveWorkbook.Worksheets ' Start of the VBA loop
For Each ws In Worksheets ' Start of the VBA loop
With ws
ws.Activate 'this part ensures each seperate tab is activated and the below code is run through
Columns("A").ColumnWidth = 0.94 'this line determines the column width
Columns("B").ColumnWidth = 6.56 'this line determines the column width
Columns("C").ColumnWidth = 13.56
Columns("D").ColumnWidth = 13.56
Columns("E").ColumnWidth = 13.56
Columns("F").ColxumnWidth = 10.11
Columns("G").ColumnWidth = 6.11
Columns("H").ColumnWidth = 10.11
Columns("I").ColumnWidth = 10.11
Columns("J").ColumnWidth = 13.56
Columns("K").ColumnWidth = 6.56
Columns("L").ColumnWidth = 6.56
Wsh.Range("A1").Select 'this part ensure each worksheet view start position is A1
ActiveWindow.View = xlPageBreakPreview 'Set Activesheet to Page Break Preview Mode
ActiveWindow.Zoom = 114 'this line sets the permanent zoom % for all tabs
ActiveWindow.ScrollColumn = 1
ActiveWindow.ScrollRow = 1
End With
Next ws
Application.Goto ThisWorkbook.Sheets("resume").Range("A1"), True 'starting position upon opening the file
'Worksheets(1).Activate 'this line make sure view is at first tab
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Calculation = xlAutomatic
ThisWorkbook.Date1904 = False
ActiveWindow.View = xlNormalView
'------ END TIMER------
TimeTaken = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "Running time was " & TimeTaken & " (hours, minutes, seconds)"
End Sub

Not able to bypass Run time error 619 in SAP connection

I have a macro to download certain SAP reports to Excel. My issue is that if I run the macro more than once in the same SAP session (first time it works fine), I get a Run time error 619 which I am not able to bypass.
For some reason (I think it's related to which server the user is logged on to), the SAP module (RE-FX) have two different variants/GUIs. Therefore, I have two different setups for downloading the report to Excel depending on the variant/GUI.
I am using the On Error Goto statement to shift between those two variants. The Run time error appears in the line following the On Error Goto statement.
As mentioned, this works fine the first time I run the macro (no Run Time error occurs and the macro jumps to the error handler as expected), but the second time I run it, the error '619' appears and it is not possible to bypass it.
I have tried the solution in this post (including Application.Wait):
Cannot Bypass Error 619 [executing SAP from VBA]
But that did not fix it (it is not the timing which is the issue here).
Sub Run_REISCDCF()
Dim Filepath As String
Dim ReportDate As String
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Filepath = ThisWorkbook.Sheets("Guide").Cells(5, 5).Text 'place to store SAP reports
'Create connection to SAP
'------------------------------------------
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children(0)
'------------------------------------------
'Removed some code to run the report and change layout (which works fine)
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
On Error GoTo XLSX_variant 'SAP has two different GUI's for RE-FX with one of them only allowing to download to a MHTML file type
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath" '<-- At this line the Run Time error appears
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
XLSX_variant:
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath"
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.XLSX"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
Try this...
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
End If
This code will lookup for the button in the session you are and if it finds it it will click on it else it means it’s not there and I’ll continue with next line.
Sub Run_REISCDCF()
Dim Filepath As String
Dim ReportDate As String
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Filepath = ThisWorkbook.Sheets("Guide").Cells(5, 5).Text 'place to store SAP reports
'Create connection to SAP
'------------------------------------------
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children(0)
'------------------------------------------
'Removed some code to run the report and change layout (which works fine)
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
'SAP has two different GUI's for RE-FX with one of them only allowing to download to a MHTML file type
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
End If
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = "Filepath" '<-- At this line the Run Time error appears
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
Thanks to #reFractil for coming up with a solution that worked!
I had to edit his solution slightly in order to embed the two variants (download SAP report as .XLSX or .MHTML), but the structure and code proposed by reFractil is the same:
'Changed code only below
'Save to Excel
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").pressToolbarContextButton "&MB_EXPORT"
session.findById("wnd[0]/usr/subSUB_AREA_ROOT:SAPLREIS_GUI_CONTROLLER:0200/subSUB_AREA:SAPLREIS_GUI_CONTROLLER:1000/cntlCC_LIST/shellcont/shell").selectContextMenuItem "&XXL"
'Solution:
If Not session.findById("wnd[1]/tbar[0]/btn[0]", False) Is Nothing Then
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Filepath
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.XLSX" 'Download as .XLSX if in "XLSX SAP_variant"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub
End If
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Filepath
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = "REISCDCF.MHTML" 'Download as .MHTML if in "MHTML SAP_variant"
session.findById("wnd[1]/tbar[0]/btn[11]").press
Exit Sub

Excel VBA custom header code works on 32-bit but not 64-bit

Context: I'm writing a list excel doc that has two sheets (Equipment List and List Inputs). I want the user to be able to input the general document info (name and date etc.) on the Inputs sheet, and this data to be captured as a snapshot and inserted into the left, centre and right header boxes. It has two different headers - one for the first page and one for every page after.
I wrote the code on excel 2013 32-bit (and it worked), only to realise that it doesn't work on any 64-bit machines. When I say it doesn't work I mean the images generated don't appear in the print preview in the header.
I'm a VBA novice and I really don't know where this code is failing, however I think it might be at the .Chart.Paste step.
I have looked into other threads on 32 to 64 bit conversion but they all reference PtrSafe which I don't think is relevant to my code.
How can I update my code to run on 64-bit?
Any advice is much appreciated.
Thanks.
Workbook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Call Module1.AddHeaderToAll_FromCurrentSheet
End Sub
Private Sub Workbook_Open()
End Sub
General (Module 1) Save_Object_As_Picture:
Sub AddHeaderToAll_FromCurrentSheet()
Dim ws As Worksheet
Dim tempFilePath As String
Dim tempPFilePath As String
Dim tempTBFilePath As String
Dim tempPic As Shape
Dim tempPrimeroPic As Shape
Dim tempTiBlkPic As Shape
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set tempPic = ThisWorkbook.Sheets("List Inputs").Shapes("RevBlkPic")
Set tempPrimeroPic = ThisWorkbook.Sheets("List Inputs").Shapes("PrimeroPic")
Set tempTiBlkPic = ThisWorkbook.Sheets("List Inputs").Shapes("TiBlkPic")
tempFilePath = Environ("temp") & "\image.jpg"
Save_Object_As_Picture tempPic, tempFilePath
tempPFilePath = Environ("temp") & "\image2.jpg"
Save_Object_As_Picture tempPrimeroPic, tempPFilePath
tempTBFilePath = Environ("temp") & "\image3.jpg"
Save_Object_As_Picture tempTiBlkPic, tempTBFilePath
For Each ws In ActiveWorkbook.Worksheets
'ws.PageSetup.FirstPage.CenterHeaderPicture
'With ActiveSheet.PageSetup.DifferentFirstPageHeaderFooter = True
'First Page Headers
ws.PageSetup.DifferentFirstPageHeaderFooter = True
ws.PageSetup.FirstPage.CenterHeader.Picture.Filename = tempFilePath
ws.PageSetup.FirstPage.CenterHeader.Text = "&G"
ws.PageSetup.FirstPage.RightHeader.Picture.Filename = tempPFilePath
ws.PageSetup.FirstPage.RightHeader.Text = "&G"
ws.PageSetup.FirstPage.LeftHeader.Picture.Filename = tempTBFilePath
ws.PageSetup.FirstPage.LeftHeader.Text = "&G"
'Different Page Headers
ws.PageSetup.RightHeaderPicture.Filename = tempPFilePath
ws.PageSetup.RightHeader = "&G"
ws.PageSetup.LeftHeaderPicture.Filename = tempTBFilePath
ws.PageSetup.LeftHeader = "&G"
ws.PageSetup.CenterHeaderPicture.Filename = tempFilePath
ws.PageSetup.CenterHeader = ""
' ws.PageSetup.RightHeaderPicture.Filename = tempPFilePath
' ws.PageSetup.RightHeader = "&G"
' ws.PageSetup.LeftHeaderPicture.Filename = tempTBFilePath
' ws.PageSetup.LeftHeader = "&G"
Next ws
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Private Sub Save_Object_As_Picture(saveObject As Object, imageFileName As String)
'Save a picture of an object as a JPG/JPEG/GIF/PNG file
'Arguments
'saveObject - any object in the CopyPicture method's 'Applies To' list, for example a Range or Shape
'imageFileName - the .gif, .jpg, or .png file name (including folder path if required) the picture will be saved as
Dim temporaryChart As ChartObject
Application.ScreenUpdating = False
saveObject.CopyPicture xlScreen, xlPicture
Set temporaryChart = ActiveSheet.ChartObjects.Add(0, 0, saveObject.Width + 1, saveObject.Height + 1)
With temporaryChart
.Border.LineStyle = xlLineStyleNone 'No border
.Chart.Paste
.Chart.Export imageFileName
.Delete
End With
Application.ScreenUpdating = True
Set temporaryChart = Nothing
End Sub

Excel VBA Code Race Condition Not Fixed by Wait, Sleep, DoEvents, etc

SOLVED! See the code below for the solution!
I have an Excel file containing multiple shape objects next to a series of text. I wrote a script to identify the location of each shape, identify how many cells to the right and down the text extends to, sets that as a range and then imports that into a chart object so I can save it as a .jpg.
The trouble is that between the creation of the chart and the pasting of the string there exists a Race Condition. If I step through the script it works fine, but as soon as I run it I get nothing but blank images.
I've tried Application.ScreenUpdating = True; Application.PrintCommunication = True; and DoEvents
I've also tried Application.Wait, but even having it wait ten seconds doesn't do the trick, when stepping through the code the chart is loaded in less than 2 seconds.
Recently I tried the kernel32 sleep method as well, and that doesn't seem to work either. Again, the amount of time I let the system sleep far exceeded my stepping. I also added all of the above methods between each line within the With statement (obviously not as a solution, but as a test) and that didn't work either..
At this point I'm completely at a loss.
If I place a stop at .Chart.Paste and then run the script (F5), and just keep hitting Run then the script works wonderfully. I just don't want users to have to sit there and hit run 600 times.
There are obvious redundancies written in between the creation of the chart and pasting of the text. This is all in the attempt at getting the code to work properly when run, and once a solution is found most of that code will be removed.
Option Explicit
Public Function ChartCheck() As String
ReCheckChart:
DoEvents
If ActiveWorkbook.ActiveSheet.ChartObjects.Count > 0 Then
GoTo ContinuePaste:
Else
GoTo ReCheckChart:
ContinuePaste:
End If
End Function
Public Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder to Save the Images In"
.AllowMultiSelect = False
If .Show -1 Then GoTo NextCode:
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Private Sub DNImageExtraction_Click()
Dim fileName As String
Dim targetWorkbook As Excel.Workbook
Dim targetWorksheet As Excel.Worksheet
Dim saveLocation As Variant
Dim saveName As String
Dim targetShape As Shape
Dim workingRange As Excel.Range
Dim bottomRow As Long
Dim workingRangeWidth As Double
Dim workingRangeHeight As Double
Dim tempChart As ChartObject
Application.ScreenUpdating = False
Application.DisplayAlerts = False
DNImageExtraction.AutoSize = False 'This is necessary to prevent the system I use from altering the font on the button
DNImageExtraction.AutoSize = True
DNImageExtraction.Height = 38.4
DNImageExtraction.Left = 19.2
DNImageExtraction.Width = 133.8
fileName = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*", , "Please select Excel file...")
Set targetWorkbook = Workbooks.Open(fileName)
Set targetWorksheet = targetWorkbook.ActiveSheet
saveLocation = GetFolder
For Each targetShape In targetWorksheet.Shapes
Set workingRange = targetWorksheet.Cells(targetShape.TopLeftCell.Row, targetShape.TopLeftCell.Column).Offset(1, 0)
saveName = workingRange.Text
If workingRange.Offset(0, 1).Value "" Then
If workingRange.Offset(1, 1).Value = "" Then
Set workingRange = Nothing
Set workingRange = targetWorksheet.Cells(targetShape.TopLeftCell.Row, targetShape.TopLeftCell.Column).Resize(, 2)
Else
bottomRow = workingRange.Offset(0, 1).End(xlDown).Row
Set workingRange = targetWorksheet.Cells(targetShape.TopLeftCell.Row, targetShape.TopLeftCell.Column).Resize((bottomRow + 2 - workingRange.Row), 2)
End If
workingRangeWidth = workingRange.Width
workingRangeHeight = workingRange.Height
End If
workingRange.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
Set tempChart = targetWorksheet.ChartObjects.Add(0, 0, workingRangeWidth, workingRangeHeight)
Application.ScreenUpdating = True
Application.PrintCommunication = True
DoEvents
Call ChartCheck
tempChart.Chart.Paste
Application.ScreenUpdating = False
tempChart.Chart.Export fileName:=saveLocation & "\DN " & saveName & ".jpg", Filtername:="JPG"
tempChart.Delete
Set tempChart = Nothing
Next
Application.Workbooks(targetWorkbook.Name).Close savechanges:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Any assistance in either a solution to the Race Condition, or re organizing the script to avoid the Race Condition altogether would be greatly appreciated.
(Code above was updated per suggestions made by Macro Man, and then re-modified once again to add in all previous suggestions on how to fix Race Condition issues after the changes were not effective.)
Consider using Application.OnTime which is good feature. It allows the scheduling of some code to be run at a certain time, most often one adds a few seconds to the current time.
Excel VBA is single-threaded and so there is no real synchronization but there is a message pump to keep order. The great thing about Application.OnTime is that it will not run despite being scheduled until the current graph of code has completed.
Because Application.OnTime uses the message pump as that is a FIFO structure it is possible to interleave the execution of code.
I think this might help here.
You can schedule a "hasItFinished" procedure which checks the existence of the shape/chart objects and if not re-schedules itself.
P.S. Can be a little tricky to debug, refactor as much code as possible outside of the procedure that you will schedule and unit test them separately. Please don't expect the lovely Edit,Debug and Continue flow that you normally get with VBA if you go down this path.
Try getting rid of the error handlers and labels, and working with objects directly instead of searching through workbook/worksheet collections. Also using meaningful variable names and proper indentation will help follow the code easily should you have any issues.
If your code works when stepping through, that usually suggests there is some issue with the use of ActiveWorkbook when workbooks are being opened/closed. Working with workbooks as objects allows us to overcome that problem because no matter if the workbook is active or not, we are always using the same instance of that workbook.
Private Sub DNImageExtraction_Click()
Dim fileName As String
Dim targetWorkbook As Excel.Workbook
Dim targetWorksheet As Excel.Worksheet
Dim saveLocation As Variant
Dim saveName As String
Dim targetShape As Shape
Dim workingRange As Excel.Range
Dim bottomRow As Long
Dim workingRangeWidth As Double
Dim workingRangeHeight As Double
Dim tempChart As ChartObject
Application.ScreenUpdating = False
Application.DisplayAlerts = False
fileName = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*", , "Please select Excel file...")
Set targetWorkbook = Workbooks.Open(fileName)
Set targetWorksheet = targetWorkbook.ActiveSheet
saveLocation = GetFolder
For Each targetShape In targetWorksheet.Shapes
Set workingRange = targetWorksheet.Cells(targetShape.TopLeftCell.Row, targetShape.TopLeftCell.Column).Offset(1, 0)
saveName = workingRange.Text
If workingRange.Offset(0, 1).value <> "" Then
If workingRange.Offset(1, 1).value = "" Then
Set workingRange = Nothing
Set workingRange = targetWorksheet.Cells(targetShape.TopLeftCell.Row, targetShape.TopLeftCell.Column).Resize(, 2)
Else
bottomRow = workingRange.Offset(0, 1).End(xlDown).Row
Set workingRange = targetWorksheet.Cells(targetShape.TopLeftCell.Row, targetShape.TopLeftCell.Column).Resize((bottomRow + 2 - workingRange.Row), 2)
End If
workingRangeWidth = workingRange.Width
workingRangeHeight = workingRange.Height
End If
workingRange.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
Set tempChart = targetWorksheet.ChartObjects.Add(0, 0, workingRangeWidth, workingRangeHeight)
With tempChart
.Chart.Paste
.Chart.Export FileName:=saveLocation & "\DN " & saveName & ".jpg", Filtername:="JPG"
.Delete
End With
Set tmpChart = Nothing
DoEvents
Next
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Outlook VBA: Activating a Workbook, Activating a Row, Inserting Copied Rows

I have an Outlook Macro that saves attachments based on a search of an e-mail inbox. The Aggregation File is then opened, then a loop opens the first of the saved attachments and copies the "AggregateThis" named range.
What I need to achieve is:
1). Activate the Aggregation File
2). Activate the Row where the result of the search for "END" is located
3). Insert the copied cells above end
The Outlook Object model is giving me trouble, this would be a total cinch in Excel VBA. Your help would mean so much!
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
.Workbooks.Open ("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
Dim x As Variant
i = -1
For Each x In AttachNames
Dim wb As Object
i = i + 1
Set wb = .Workbooks.Open("J:\Retail Finance\Varicent\General Teamshare Resources\Teamshare AAA\" & AttachNames(i))
Set wb = .Worksheets("Additional Assignment Bonus FRM")
'Copies the "Aggregate This" named range from the Individual File (i)
With wb.Range("AggregateThis")
.Copy
End With
'Switches focus to Aggregation File
Set wb = .Workbooks("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
With wb
.Activate '#1). I want to put focus on this file it throws an error
End With
'Find EndRow in the Aggregation File
Set wb = .Worksheets("Additional Assignment Bonus FRM").Cells.Find("End")
With wb
.ActivateRow '#2).This throws an error
.PasteSpecialInsertRows '#3). This doesnt work
End With
Next
The original code didn't work properly because, for .Activate to work, ScreenUpdating must be set to True (which it is by default).
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = True '## Was set to False in code originally##
.Workbooks.Open ("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
Dim x As Variant
i = -1
For Each x In AttachNames
Dim wb As Object
i = i + 1
Set wb = .Workbooks.Open("J:\Retail Finance\Varicent\General Teamshare Resources\Teamshare AAA\" & AttachNames(i))
With xlApp
.Worksheets("Additional Assignment Bonus FRM").Range("AggregateThis").Copy 'Copies Range
End With
Set wb = .Workbooks.Open("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
With wb
.Worksheets("Additional Assignment Bonus FRM").Rows.Find("End").Select
.Worksheets("Additional Assignment Bonus FRM").Activerange.Paste '##This needs to be fixed##, will edit response soon.
End With
Next
End With
End Sub

Resources