VBA Workbook_Open() doesn't always work - vba

I am trying to run this simple VBA code when opening excel workbook.
Private Sub Workbook_Open()
Application.CommandBars.ExecuteMso ("HideRibbon")
ActiveWindow.DisplayHorizontalScrollBar = False
ActiveWindow.DisplayHeadings = False
ActiveWindow.DisplayGridlines = False
Application.DisplayFormulaBar = False
End Sub
However, this works 50% of times and I'm still wondering why. In one of the sheet there is conditional formatting that I have to keep for reporting purposes). I have tried many solutions suggested in this community but they didn't work at all.
Can somebody help me to figure it out?
Many thanks

Related

VBA Excel: Application.DisplayAlerts not working if called from another macro

I've got a macro opening another workbook that can be readonly. To avoid readonly alerts I switch Application.DisplayAlerts propery to False, like this
Sub tmp()
Application.DisplayAlerts = False
Debug.Print Application.DisplayAlerts
Workbooks.Open "\\Co-file01\FileName.xlsx"
End Sub
And it works fine, but if I call it from another macro, like this
Sub tmp1()
Application.Run "tmp"
End Sub
I still get the alert, and the code stops working, waiting for response. The line
Debug.Print Application.DisplayAlerts
returns False, so it seems the property is really switched, but for some reason it does'not apply.
Can anyone explain the reasons it works this way and suggest any workaround?
I'm working with Excel 2016 64bit, Windows 7 if matters
jkpieterse suggested the answer
You should call the macro directly by its name: simply type tmp1 on a
new line, rather than using application.run

VBA getting error Active method of Worksheet class failed

I tried to look for answers but am not finding anything that has worked so far. I have some code that works for some people and doesn't work for others (using same version of Excel) when running this code:
Private Sub Workbook_Open()
Application.ScreenUpdating = False
Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",False)"
Application.DisplayFormulaBar = False
Sheets("Discount").Activate
ActiveSheet.Unprotect Password:="01"
ActiveSheet.Range("G14:O15,O18:O19,D29:I29,D31:I31,D33:I33,D35:I35,D37:I37").ClearContents
ActiveSheet.Shapes("Option Button 31").ControlFormat.Value = xlOn
OptionButton31_Click
Application.ScreenUpdating = True
End Sub
The error shows up at Sheets.("Discount").Activate
the spelling of the worksheet is correct. I also tried
Private Sub Workbook_Open()
ActiveWorkbook.Unprotect Password:="01"
Application.ScreenUpdating = False
Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",False)"
Application.DisplayFormulaBar = False
ThisWorkbook.Sheets("Discount").Activate
ActiveSheet.Unprotect Password:="01"
ActiveSheet.Range("G14:O15,O18:O19,D29:I29,D31:I31,D33:I33,D35:I35,D37:I37").ClearContents
ActiveSheet.Shapes("Option Button 31").ControlFormat.Value = xlOn
OptionButton31_Click
ActiveWorkbook.Protect Password:="01"
Application.ScreenUpdating = True
And still getting the error. I am having a hard time figuring it out because it works for me every time, but doesn't for other people.
Solution 1:
Instead of Sheets.("Discount").Activate write Sheets("Discount").Activate and it should work. E.g., remove the dot.
Solution 2:
If this does not work, try to make sure that this sheet is visible. E.g. write before the line with the error the following:
Sheets("Discount").Visible = True
In general, in VBA try to avoid ActiveSheet, ActiveWorkbook, ActiveCell -
How to avoid using Select in Excel VBA
As noted by #Mat's Mug, consider using Worksheets("Discount").Visible, when you refer to Worksheets, because the Sheets collection contains Charts as well.
Try using:
Sheets("Discount").Visible
Sheets("Discount").Select
If this doesn't work, let me know and I'll see if there's anything else I can recommend. If you make a note of any error messages, this may help. Also, try running it with screenupdating not turned off as the person above suggested - then you will see if there's a specific action that's making it fall over.

How To Speed Up VBA Code

I have an excel file with a VBA code (Not written by me)
How this code works is user enters a 6 digit number in a user form, the VBA then checks another sheet and if this 6 digit number is present on the worksheet.
If it does, it changes the stage, but if it doesn't it adds this 6 digit number to the worksheet
It used to work perfectly, but now because the excel file has grown in the number of rows, almost 6000 rows, this code is become very slow, takes up to 20 seconds to update the sheet
Can someone please help me speed this code up, or suggest another way to acheive it
The code is below
Private Sub cmdPSDUdate_Click()
Dim x
If (Me.PSDUDateRow = "") + (Me.PSDStageCB.ListIndex = -1) Then Exit Sub
With Sheets("psdata stage cals").ListObjects("PSDataStageCals")
x = Application.Match(Val(Me.PSDUDateRow), .ListColumns(1).DataBodyRange, 0)
If IsNumeric(x) Then
.ListRows(x).Range(2) = Me.PSDStageCB.Value
Else
.ListRows.Add.Range = Array(Val(Me.PSDUDateRow), Me.PSDStageCB)
End If
End With
Me.PSDUDateRow.Value = ""
Me.PSDStageCB.Value = ""
Me.PSDUDateRow.SetFocus
End Sub
Thanks in advance
Rahul
You could turn off screenupdating, automatic calculations etc
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
‘Place your macro code here
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
In general, there are two ways to speed up VBA code:
Write good code, that does not use Select, Activate, ActiveCell, Selection etc - How to avoid using Select in Excel VBA
Refer to these routines on the start and on the end of the code:
Public Sub OnEnd()
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.AskToUpdateLinks = True
Application.DisplayAlerts = True
Application.Calculation = xlAutomatic
ThisWorkbook.Date1904 = False
Application.StatusBar = False
End Sub
Public Sub OnStart()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Calculation = xlAutomatic
ThisWorkbook.Date1904 = False
ActiveWindow.View = xlNormalView
End Sub
(For improvement ideas, kindly make PullRequest)
I think that Calculation should be always set to xlAutomatic, as far as if you need xlCalculationManual to speed up, it is a good idea to refactor the code. Furthermore manual calculation is too risky.
The same goes for Date1904 - it is always set to False.
In addition to the tweaks suggested by Storax, your code is slow because you are bringing data cell-by-cell over the Excel/VBA divide.
Furthermore, you can radically speed up your MATCH function by using the Binary version of it. Have a read of http://dailydoseofexcel.com/archives/2015/04/23/how-much-faster-is-the-double-vlookup-trick/ and also try to minimise the amount of individual transfers you do across the Excel/VBA divide by either performing the lookups entirely within the Excel sheet (by using VBA to write the formula in the sheet and execute it there) or by bringing all the data into VBA in one go using variant arrays, performing your logic, and then by dumping it back in one go. Google "Efficient way to transfer data between Excel and VBA" or something similar. Also check out any articles from Charles Williams on the subject.
I don't see anything wrong with your code. Perhaps the Workbook itself is the culprit. Is it becoming huge and slow to open ?
If yes, try searching for 'cleanup excel file'.
Some results I found:
https://excelfilecleaner.codeplex.com/
https://support.microsoft.com/en-us/help/3070372/how-to-clean-up-an-excel-workbook-so-that-it-uses-less-memory
When crunching large chunks of data in Excel that requires frequent referencing of cells, it’s always much much faster to copy the data to an array (copy the entire worksheet if necessary), process the data within the array, and then write back to the worksheet if necessary. Copying data from worksheet to array is a one line command that is very very fast. Same with array to worksheet. Relatively speaking, referencing cells is a very time consuming process compared with referencing elements of an array.

Excel/VBA - How do I use BloombergUI .Subscribe to pull BDS?

I am running into a problem where Bloomberg formulas do not load while the VBA is running. I would like to use the BloombergUI to resolve it.
Colin Legg's response here works for pulling BDP data, but I cannot get it to work for BDS formulas. Does anybody know how to modify the code?
Dim xlCalc As XlCalculation Sub Test1()
'early bound - reference to Bloomberg
'save the calculation setting and then set to automatic
xlCalc = Application.Calculation
Application.Calculation = xlCalculationAutomatic
Sheet1.Range("C2:H4").Formula = "=BDP($B2,C$1)"
BloombergUI.RefreshAllStaticData
Application.OnTime Now + TimeValue("00:00:02"), "HardCode" End Sub Sub HardCode()
Sheet1.Range("C2:H4").Value = Sheet1.Range("C2:H4").Value
Application.Calculation = xlCalc End Sub
I think you're looking for something like one of these:
Excel Bloomberg API callback in macro
VBA to refresh Bloomberg data not running in proper order
If you need to use the values returned by Bloomberg in VBA, you need to wait for all the values to return first.

DisplayFullScreen and DisplayFormulaBar Not Playing Well Together

I was making an application and I went to hide the formula bar and make it full screen in my Workbook_Activate event, then show the formula bar and make it windowed(is that a word?) in my Workbook_Deactivate event. I actually struggled with this for a while. I kept having a problem with the formula bar showing up when it wasn't supposed to or disappearing when I wanted it there. I finally got it to work by making sure I used the DisplayFullScreen first and only then using the DisplayFormulaBar method.
Does anyone know why you would need to put these in a specific order for them to work together? I couldn't find anything when I was looking for it.
I'm using Excel 2010.
EDIT: Here's my code.
Private Sub Workbook_Activate()
Application.ScreenUpdating = False
ThisWorkbook.Sheets(2).Activate
ActiveWindow.DisplayGridlines = False
ActiveWindow.DisplayHeadings = False
ThisWorkbook.Sheets(1).Activate
ActiveWindow.DisplayGridlines = False
ActiveWindow.DisplayHeadings = False
Application.DisplayFullScreen = True
Application.DisplayFormulaBar = False
Application.ScreenUpdating = True
End Sub
Private Sub Workbook_Deactivate()
Application.DisplayFullScreen = False
Application.DisplayFormulaBar = True
End Sub
This is from the MSDN documentation: "Toolbars, the status bar, and the formula bar maintain separate display settings for full-screen mode and normal mode."
https://msdn.microsoft.com/en-us/library/office/ff838060.aspx
I was searching for mostly DisplayFormulaBar topics since that was what was showing up strangely for me. Hopefully this helps anyone who searches for it in the future.