VBA/Excel - clipboard empty after workbook SaveAs - excel

After 10 years, I find myself making my first post. I've search endlessly for a solution to no avail. I want to:
copy a range of cells
save and close the workbook
user can paste to another application
I haven't even closed the workbook in the code below, yet there's nothing on the clipboard after the SaveAs.
Sub Test()
Application.CutCopyMode = True
ActiveWorkbook.Sheets(1).Range("A1:C5").Copy
ActiveWorkbook.SaveAs Filename:="F:\Test.xlsx"
End Sub
Setting CutCopyMode to False yields the same results. I can paste no problem if I exclude the SaveAs line.

Since there are no changes to the workbook after you save, you can simply switch the lines and get your desired end result.
Sub Test()
Application.CutCopyMode = True
ActiveWorkbook.SaveAs Filename:="F:\Test.xlsx"
ActiveWorkbook.Sheets(1).Range("A1:C5").Copy
End Sub

Related

VBA: Excel Crashes on last Macro (when sheet is deleted)

I wrote several macros for workbook and I have noticed that all the macros run but then at the last action, Excel crashes.
After much troubleshooting, I found the trigger: "Activesheet.move" or "Activesheet.delete." It seems whenever a sheet is deleted from a workbook (or moved to a new workbook), Excel crashes.
Below is the final macro which triggers Excel to crash. The workbook (Template.xlsm) has 3 other sheets so deleting one should not prompt it to close. Essentially, I press the "FinishButton" which is assigned the SaveTemplate() macro. The Macro makes sure there is data in D8 before continuing. It then deletes the "FinishButton" before deleting the activesheet.
Can someone please advise what I am doing wrong or what is causing the crash?
Sub SaveTemplate()
Dim dtToday As String
Dim workdoc As String
dtToday = Format(Date, "mm_dd_yyyy")
workdoc = "Working_Doc_" & dtToday
Workbooks("Template.xlsm").Activate
If Sheets(workdoc).Range("D8").Value = "" Then Exit Sub
Sheets(workdoc).Unprotect Password:="password"
Sheets(workdoc).Shapes.Range(Array("FinishButton")).Select
Selection.Delete
Sheets(workdoc).Protect Password:="password"
Application.DisplayAlerts = False
Sheets(workdoc).Delete
Application.DisplayAlerts = True
Workbooks("Template.xlsm").Save
End Sub
Thank you

Excel VBA update chart not visible

I have an excel file which iterates over different excel files to update them and create a PDF file from them.
The macro iterates over rows and opens the files. This code opens the files:
Private Sub openFile(row As Integer)
Dim filePath As String
Dim wb As Workbook
filePath = Application.ActiveWorkbook.Path + "\" + allRows(row).filename
Set wb = Workbooks.Open(filePath)
Application.Run "RefreshEntireWorksheet"
Application.OnTime Now + (TimeSerial(0, 1, 59)), "'ThisWorkbook.updateCharts """ & row & "'"
Application.OnTime Now + (TimeSerial(0, 2, 59)), "'ThisWorkbook.createEmail'"
End Sub
Now if there are multiple files, only 1 file has the charts properly updated (the file being on the front). It seems like the updateCharts code doesn't work at all:
Sub updateCharts(row As Integer)
Dim SheetName As String
Dim wb As Workbook
SheetName = "Sheet1"
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Set wb = Workbooks(allRows(row).filename)
wb.Activate
wb.Sheets(SheetName).Activate
For Each cht In wb.Sheets(SheetName).ChartObjects
cht.Chart.Refresh
DoEvents
Next cht
End Sub
I checked following links for answers, but none helped:
Can't refresh a chart in Excel VBA (Excel 2016)
Refresh all charts without blinking
excel chart not updating when data changed by vba
Excel 2013 vba refresh chart content after each iteration of For Loop
They all suggest to add an DoEvent, but that doesn't work. So the question is, how can I update charts in a different workbook via VBA?
I have encountered similar issues in the past, and have observed that they seem to increase as the Version of Excel increments; I suspect it is a case of falling afoul of side-effects caused efficiency enhancements elsewhere to speed up the Application in general (reducing unnecessary drawing on the screen, et cetera)
One thing that I have found (sometimes) works is to try and force the Application Window to Refresh/Redraw, by setting the WindowState to itself:
Application.WindowState = Application.WindowState
This is similar to how some people suggest using ActiveWindow.SmallScroll down:=0, ActiveWindow.SmallScroll 0, ActiveWindow.SmallScroll, or ActiveWindow.SmallScroll down:=1: ActiveWindow.SmallScroll up:=1
Combining this with the ScreenUpdating toggle, and the DoEvents, you can create a quick Subroutine like this:
Public Sub RedrawScreen()
Dim ScreenUpdating As Boolean
ScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = True
Application.WindowState = Application.WindowState
DoEvents
Application.ScreenUpdating = ScreenUpdating
End Sub
Try this (it works for me - Excel 2016):
DoEvents must be in your code as others said before
Delete all colours of the cells of the spreadsheet: all the background of the cells must be "no background"; use only automatic colour (black) for the text of all the cells.
Save, close and reopen the file. Now start your macro and look at your chart.
I don't know why it works, but.........it works!
For those more capable than me: do the opposite: if your chart is updating with your macro running, try to colour some text or some cells. The chart will not update anymore. The Microsoft experts should check what is happening.
Hope this helps. Bye, bb.

Excel BBG formulas not refreshing

I am trying to write a basic script to open another file, refresh the data in that file, save that updated file off as values (not formulae), and then closes the originally opened file containing the formulas without saving. My issue is that the file doesn't actually pull the requested formulae until after the macro has finished and the 'updated' file has saved itself away. In other words the formulae start to refresh, apparently never finish refreshing, and then copy/paste over themselves with the "#N/A Requesting Data..." string, instead of the actual data. I've seen a number of simlar questions around about this, but I haven't seen one which defines why the issue exists in the first place. I have tried runnign the refresh and the saving in different subs, and have tried a number of different methos of waiting for the formulae to finish refreshing, without avail. E.g.:
'ATTEMPT 1
'Application.Calculate
'If Not Application.CalculationState = xlDone Then
' DoEvents
'End If
'ATTEMPT 2
'Do: DoEvents: Loop While Application.CalculationState = xlCalculating
'ATTEMPT 3
'Do Until ActiveSheet.CalculationState = xlDone
' DoEvents
'Loop
Here is the code which runs once the initiating file is openend:
Sub Auto_Open()
Call Refresh
'COPY PASTE VALUES
ActiveSheet.Cells.Copy
'COPY UPDATED SHEET TO NEW BOOK & SAVE AS .XLS
Workbooks.Add
With ActiveSheet
.Cells.PasteSpecial xlValues
.Cells.PasteSpecial xlFormats
End With
Application.CutCopyMode = False
ActiveWorkbook.SaveAs (NewBook & Format(Now(), "DD-MMM-YYYY hh mm AMPM") & ".xls")
End Sub
Here is the sub which actually refreshes the data:
Sub Refresh()
Application.Calculation = xlCalculationManual 'ENSURE IT ONLY PULLS DATA WHEN YOU TELL IT TO
Dim wkbook As Workbook
Dim OpenedBook As String
OpenedBook = "G:\Folder Name\Sub Folder\File Opened in Folder.xlsx" 'FULL PATH OF WORKBOOK TO BE OPENED
NewBook = "G:\Folder Name\Sub Folder\File Saved in Folder\" 'BASE NAME OF THE SAVED WORKBOOK
'OPEN THE DESIRED WORKBOOK
Set wkbook = Workbooks.Open(OpenedBook)
wkbook.Activate
'REFRESH ALL BBG FORMULAE
Application.Run "RefreshAllWorkbooks"
Application.Run "RefreshAllStaticData"
Application.Wait (Now + TimeValue("00:00:10"))
End Sub
The actual formula being refreshed work otherwise, and are straighforward BBG BDH formulae. E.g. =BDP(B3&" curncy", "px_mid") where B3 has a currency pair like "EURUSD". Any thoughts on why the formulae are not pulling, even after the Wait and DoEvents 'fixes'? I have a feleing I am misunderstanding something fundamental about how BBG/VBA works, so please help me understand why this situation exists in the first place. Thanks in advance!

Copy a sheet to an open workbook without leaving the current workbook?

I'm new to VBA code. So far I have successfully managed to copy the sheet I want to another open workbook. How can I do this without leaving the current workbook?
I've dug around for answers and tried Application.ScreenUpdating = False but that doesn't seem to have any effect, perhaps I'm not using this correctly?
Here's what I've got so far, its fairly simple but it works so far as copying the sheet.
Sub Sample1()
Application.ScreenUpdating = False
Workbooks("Workbook1.xlsm").Sheets("Sheet1").CopyAfter:=Workbooks("Workbook2.xlsm").Sheets("Copy_After")
Application.ScreenUpdating = True
End Sub
All you have to do is record which sheet was the ActiveSheet on the begining of your script and Activate it once your script finishes.
Sub Sample1()
Dim OriginalSheet as Worksheet
Application.ScreenUpdating = False
OriginalSheet = ActiveSheet
Workbooks("Workbook1.xlsm").Sheets("Sheet1").CopyAfter:=Workbooks("Workbook2.xlsm").Sheets("Copy_After")
OriginalSheet.Activate
Application.ScreenUpdating = True
End Sub

Excel Vba stops excution after deleting sheet

I am new to VBA. I have written a code to delete a particular sheet. After execution of that delete sheet macro, excel macro stopped execution. It didnt execute futher..
Here is my code..
Sub CopyAcross()
Dim sheetName As String
sheetName = "Master_Base"
If WorksheetExists(sheetName) Then
DeleteSheet (sheetName)
End If
MsgBox "Debug"
Workbooks("Master_Base.csv").Sheets("Master_Base").Copy Before:=Workbooks("Copy of test.xlsm").Worksheets("Sheet3")
End Sub
Sub DeleteSheet(strSheetName As String)
' deletes a sheet named strSheetName in the active workbook
Application.DisplayAlerts = False
Sheets(strSheetName).Delete
Application.DisplayAlerts = True
End Sub
Can any one help on this,
Thanks in advance.
I was experiencing the same issue, on a Windows 7 computer with Excel version 16.0.10730.20264 32-bit, the code ran fine without issue. However, on a Windows 10 computer with the same Excel install version, the macro would immediately stop execution following the Sheets.Delete line.
I found that this was only happening where I was attempting to manipulate a workbook that contained VBA code, that I had opened during the macro.
The issue is caused by the macro security settings on the computer. If you set Automation Security to Low before opening the workbook, you should no longer get the error:
Use the code:
Application.AutomationSecurity = msoAutomationSecurityLow
Since you are working with multiple workbooks, use objects. Else your code MAY work with the wrong workbook/worksheet
Try this (UNTESTED)
Sub CopyAcross()
Dim wbI As Workbook, wbO As Workbook
'~~> The workbook from where the code is running
Set wbO = ThisWorkbook
'~~> Here you open the csv
Set wbI = Workbooks.Open("E:\OPM\OPM Sheet\Master_Base.csv")
'~~> This will delete the sheet if it exists
'~~> no need to check if it exists
On Error Resume Next
Application.DisplayAlerts = False
wbO.Sheets("Master_Base").Delete
Application.DisplayAlerts = True
On Error GoTo 0
'~~> The csv will always have 1 sheet
'~~> so no need providing a name
wbI.Sheets(1).Copy Before:=wbO.Worksheets("Sheet3")
End Sub

Resources