I'm using Excel Introp for a .net application to embed an Excel workbook in a windows userform.
excApp.Visible = False
wb = excApp.Workbooks.Open(directOpenPath) ' , [ReadOnly]:=False, IgnoreReadOnlyRecommended:=True)
wb.Saved = True ' necessary to prevent Excel has stopped working error and to not actually do a save
hwnd1 = CType(excApp.Hwnd, IntPtr)
SetParent(excApp.Hwnd, pnlExcel.Handle)
SendMessage(excApp.Hwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0)
MoveWindow(hwnd1, 0, 0, pnlExcel.Width, pnlExcel.Height, True)
excApp.Visible = True
There are ActiveX buttons on the worksheet that work fine when I open using the above code.
However, it is my desire to make the object look less like Excel so I wanted to hide the ribbon, formula bar, etc.
I added the line: excApp.DisplayFullScreen=True. Upon doing that, clicking on a button no longer kicked off the associated macro. Additionally, I could no longer click on any cell in the worksheet. This seems like odd behavior but I have traced it down to the DisplayFullScreen line.
Also I am trying to include the following:
excApp.ActiveWindow.DisplayWorkbookTabs = False
excApp.ActiveWindow.DisplayHeadings = False
excApp.ActiveWindow.DisplayGridlines = False
But I get a object not set to reference error. If I add excApp.ActiveWindow.Activate, the worksheet "locks up" again and I can't click on any cells.
Any ideas?
Related
I have just written this easy macro in Excel VBA for merging a group of selected cells:
Sub Macro_Merge()
Dim Temp As String
Dim S As Variant
Temp = ""
For Each S In Selection
If Temp = "" Then
Temp = CStr(S.Value)
Else:
Temp = Temp + "," + CStr(S.Value)
End If
Next
Selection.Merge
Selection.Value = Temp
Selection.VerticalAlignment = xlTop
End Sub
This works fine, but I always see that annoying dialog box, warning me about loosing data while merging (which is exactly what I'm trying to avoid in my macro).
I can get rid of that dialog box, configuration the Application's DisplayAlerts property:
Application.DisplayAlerts = False
Selection.Merge
Selection.Value = Temp
Application.DisplayAlerts = True
This is working fine.
So, as Application is the default object, I tried to clean up my code, as follows:
DisplayAlerts = False
Selection.Merge
Selection.Value = Temp
DisplayAlerts = True
As you see, I simply omit mentioning the Application object. This is something which is allowed and I've done in the past. (If not in VBA, then Delphi, maybe?)
... but to my surprise, the dialog box appears again (although pressing F1 brings me to the official "Application.DisplayAlerts" documentation).
This leaves me with a simple question:
If a simple DisplayAlerts = ... does not equal Application.DisplayAlerts = ... anymore, what does it mean and how can I use it?
For your information, I'm working with Excel-365.
DisplayAlerts is an undeclared variable.
Certain Application properties and methods can (effectively) have the Application omitted:
ActiveCell, ActiveSheet, ActiveWorkbook, ActiveWindow, Addins, Charts, Selection, etc.
Calculate, Evaluate, Intersect, Run, Union, etc.
(but see this answer why/how this works):
A boolean property such as DisplayAlerts (EnableEvents, ScreenUpdating, etc) doesn't fall into the above category.
A golden rule in order not to fall into such a trap is the usage of Option Explicit while writing macros.
Just to add some information to the answer of #BigBen. If you write something like Workbooks or ActiveSheet in your code, VBA is not looking into the Application-object - it is looking into a (rather well hidden) object named Global.
The global object is exposing some (but not all) properties and methods of the Application-object, so ActiveSheet is referring to Application.ActiveSheet - but not because the Application has a member with this name but because the Global object defines that ActiveSheet means Application.ActiveSheet. In fact even the Application-object is accessed via the Global object.
There is hardly any information about this Global object or its concept. I found a page from Microsoft describing the Global object of MS Word, but the only explanation there is "Contains top-level properties and methods that don't need to be preceded by the Application property.". For Excel, I found this page on O'Reilly.
From time to time you get strange error messages like "Excel VBA Method 'Range' of object'_global' failed" - this is a pointer to the Global object. I would be glad to learn more about the concepts and mechanics of this object, but I am afraid that there are only very few people around that know more (except of course Mathieu Guindon AKA Mr. Rubberduck...). In daily life, we take it for granted that things like ActiveSheet simply works.
I have a script that opens an Excel spreadsheet and then goes to a specific sheet before running a macro. The problem is that this macro brings up different dialog boxes which require user input - I am trying to automate the process. I have tried to get rid of these boxes by using the following code:
import os
impor win32com.client
xl = win32com.client.Dispatch('Excel.Application')
xl = DisplayAlerts = False #Supposed to disable alert/messages/dialog boxes
wb = xl.Workbooks.Open(os.path.abspath('Test.xlsm'), ReadOnly = 0) #Opens spreadsheet
wb.Worksheets('Assets').Activate() #Activates correct sheet
wb.Application.Run('MxRunAction') #Runs macro
wb.Clost(True)
I have read on many threads that:
Application.DisplayAlerts = False
is supposed to fix this problem, yet this seems to do nothing if I substitue Application with xl for my case. Am I using it properly in this sense?
That would be the Application need to be closed
xl.DisplayAlerts = False
When my Office Writer Excel report opens, it randomly un-hides some of the hidden cells and columns. I have verified that it is not the data that causes the columns or cells to not be hidden. Has anyone experienced this before and is there a way to make sure that all columns or cells stay hidden when the excel file is opened?
I work for SoftArtisans. We have not had any other reports of programmatically hidden columns becoming visible in the output file. We also have not been able to reproduce the behavior you are reporting. It would be helpful to see a code snippet, as well as to know which version of OfficeWriter you are using and which version of Excel is being used to open the output file.
There are two ways to hide columns with our API, both using the ColumnProperties object. You can set the hidden property to true or set the width property to zero. You could do both if you like, although that shouldn't be necessary.
For example:
ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Create(ExcelApplication.FileFormat.Xlsx);
//or if opening an existing workbook
//Workbook wb = xla.Open(inputFilePath);
//Get a handle on the worksheet
Worksheet ws = wb.Worksheets[0];
//Write a value to a cell
ws.Cells[0, 9].Value = "Hidden Value";
//Get a handle on the column you want to hide
ColumnProperties colProps = ws.GetColumnProperties(9);
//set the column to hidden
colProps.Hidden = true;
//or set the column width to zero
colProps.Width = 0;
//Stream the output file to the response
xla.Save(wb, Page.Response, "HiddenColumnTest.xlsx", false);
How can I stop a button from resizing? Each time I click on the button, either the size of the button or the font size changes.
Note: I cannot lock my sheet as my Macro will write into the sheet.
Autosize is turned off. I run Excel 2007 on Windows 7 (64 Bit).
I use the following for ListBoxes. Same principle for buttons; adapt as appropriate.
Private Sub myButton_Click()
Dim lb As MSForms.ListBox
Set lb = Sheet1.myListBox
Dim oldSize As ListBoxSizeType
oldSize = GetListBoxSize(lb)
' Do stuff that makes listbox misbehave and change size.
' Now restore the original size:
SetListBoxSize lb, oldSize
End Sub
This uses the following type and procedures:
Type ListBoxSizeType
height As Single
width As Single
End Type
Function GetListBoxSize(lb As MSForms.ListBox) As ListBoxSizeType
GetListBoxSize.height = lb.height
GetListBoxSize.width = lb.width
End Function
Sub SetListBoxSize(lb As MSForms.ListBox, lbs As ListBoxSizeType)
lb.height = lbs.height
lb.width = lbs.width
End Sub
I added some code to the end of the onClick thus:
CommandButton1.Width = 150
CommandButton1.Height = 33
CommandButton1.Font.Size = 11
Seems to work.
I got the issue a slightly different way. By opening the workbook on my primary laptop display, then moving it to my big monitor. Same root cause I would assume.
Seen this issue in Excel 2007, 2010 and 2013
This code prevents the issue from manifesting. Code needs to run every time a active X object is activated.
Sub Shared_ObjectReset()
Dim MyShapes As OLEObjects
Dim ObjectSelected As OLEObject
Dim ObjectSelected_Height As Double
Dim ObjectSelected_Top As Double
Dim ObjectSelected_Left As Double
Dim ObjectSelected_Width As Double
Dim ObjectSelected_FontSize As Single
ActiveWindow.Zoom = 100
'OLE Programmatic Identifiers for Commandbuttons = Forms.CommandButton.1
Set MyShapes = ActiveSheet.OLEObjects
For Each ObjectSelected In MyShapes
'Remove this line if fixing active object other than buttons
If ObjectSelected.progID = "Forms.CommandButton.1" Then
ObjectSelected_Height = ObjectSelected.Height
ObjectSelected_Top = ObjectSelected.Top
ObjectSelected_Left = ObjectSelected.Left
ObjectSelected_Width = ObjectSelected.Width
ObjectSelected_FontSize = ObjectSelected.Object.FontSize
ObjectSelected.Placement = 3
ObjectSelected.Height = ObjectSelected_Height + 1
ObjectSelected.Top = ObjectSelected_Top + 1
ObjectSelected.Left = ObjectSelected_Left + 1
ObjectSelected.Width = ObjectSelected_Width + 1
ObjectSelected.Object.FontSize = ObjectSelected_FontSize + 1
ObjectSelected.Height = ObjectSelected_Height
ObjectSelected.Top = ObjectSelected_Top
ObjectSelected.Left = ObjectSelected_Left
ObjectSelected.Width = ObjectSelected_Width
ObjectSelected.Object.FontSize = ObjectSelected_FontSize
End If
Next
End Sub
(Excel 2003)
It seems to me there are two different issues:
- resizing of text of ONE button when clicking on it(though not always, don't know why), and
- changing the size of ALL buttons, when opening the workbook on a display with a different resolution (which subsist even when back on the initial display).
As for the individual resizing issue: I found that it is sufficient to modify one dimension of the button to "rejuvenate" it.
Such as :
myButton.Height = myButton.Height + 1
myButton.Height = myButton.Height - 1
You can put it in each button's clicking sub ("myButton_Click"), or implement it
a custom Classe for the "onClick" event.
I experienced the same problem with ActiveX buttons and spins in Excel resizing and moving. This was a shared spreadsheet used on several different PC's laptops and screens. As it was shared I couldn't use macros to automatically reposition and resize in code.
In the end after searching for a solution and trying every possible setting of buttons. I found that grouping the buttons solved the problem immediately. The controls, buttons, spinners all stay in place. I've tested this for a week and no problems. Just select the controls, right click and group - worked like magic.
Use a Forms button rather than an ActiveX one, ActiveX controls randomly misbehave themselves on sheets
Do you have a selection command in the buttons macro?
Shortly after I renamed some cells in a worksheet including one that the toggle button selects after its toggle function, the font size shrunk. I fixed this by making sure Range("...").Select included the new cell name, not the coordinates.
It happens when the screen resolution / settings change after Excel has been open.
For example:
Open a workbook that has a button on it
Log in with Remote Desktop from a computer with different screen size
Click on the button => the button size will change
The only solution I found is to close Excel and reopen it with the new screen settings. All instances of Excel must be closed, including any invisible instance executed by other processes without interface must be killed.
Old issue, but still seems to be an issue for those of us stuck on Excel 2007. Was having same issue on ActiveX Listbox Object and would expand its size on each re-calculate. The LinkCells property was looking to a dynamic (offset) range for its values. Restructuring so that it was looking to a normal range fixed my issue.
I had this problem using Excel 2013. Everything for working fine for a long time and all of sudden, when I clicked on the button (ActiveX), it got bigger and the font got smaller at the same time.
Without saving the file, I restarted my computer and open the same Excel file again and everything is fine again.
Mine resized after printing and changing the zoom redrew the screen and fixed it
ActiveWindow.Zoom = 100
ActiveWindow.Zoom = 75
Found the same issue with Excel 2016 - was able to correct by changing the height of the control button, changing it back, then selecting a cell on the sheet. Just resizing did not work consistently. Example below for a command button (cmdBALSCHED)
Public Sub cmdBALSCHED_Click()
Sheet3.cmdBALSCHED.Height = 21
Sheet3.cmdBALSCHED.Height = 20
Sheet3.Range("D4").Select
This will reset the height back to 20 and the button font back to as found.
After some frustrated fiddling, The following code helped me work around this Excel/VBA bug.
Two key things to note that may help:
Although others have recommended changing the size, and then immediately changing it back, notice that this code avoids changing it more than once on single toggle state change. If the value changes twice during one event state change (particularly if the second value is the same at the initial value), the alternate width and height properties may not ever be applied to the control, which will not reset the control width and height as it needs to be to prevent the width and height value from decreasing.
I used hard-coded values for the width and height. This is not ideal, but I found this was the only way to prevent the control from shrinking after being clicked several times.
Private Sub ToggleButton1_Click()
'Note: initial height is 133.8 and initial width was 41.4
If ToggleButton1.Value = True Then
' [Code that I want to run when user clicks control and toggle state is true (not related to this issue)]
'When toggle value is true, simply change the width and height values to a specific value other than their initial values.
ToggleButton1.Height = 40.4
ToggleButton1.Width = 132.8
Else
' [Code that I want to run when user clicks control and toggle state false (not related to this issue)]
'When toggle value is false adjust to an alternate width and height values.
'These can be the same as the initial values, as long as they are in a separate conditional statement.
ToggleButton1.Height = 41.4
ToggleButton1.Width = 133.8
End If
End Sub
For a control that does not toggle, you may be able to use an iterator variable or some other method to ensure that the width and height properties alternate between two similar sets of values, which would produce an effect similar the toggle state changes that I used in this case.
Reference Excel VBA to SQL Server without SSIS
After I got the above working, I copied all the global variables/constants from the routine, which included
Const CS As String = "Driver={SQL Server};" _
& "Server=****;" _
& "Database=****;" _
& "UID=****;" _
& "PWD=****"
Dim DB_Conn As ADODB.Connection
Dim Command As ADODB.Command
Dim DB_Status As Stringinto a similar module in another spreadsheet. I also copied into the same module
Sub Connect_To_Lockbox()
If DB_Status <> "Open" Then
Set DB_Conn = New Connection
DB_Conn.ConnectionString = CS
DB_Conn.Open ' problem!
DB_Status = "Open"
End If
End SubI added the same reference (ADO 2.8)
The first spreadsheet still works; the seccond at DB_Conn.Open pops up "Run-time error '-214767259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Removing the references on both, saving files, re-opening, re-adding the references doesn't help. The one still works and the other gets the error.
?!?
I observed the same error message and in my case nothing had changed. I wondered if my odbc driver needed to be reinstalled (based on what i read online). In any case, restarting excel did the trick. Sometimes the solution is much simpler. :-)
When the error pops up, check your "locals" windows to see what the CS holds. View > Locals Window
Problem: Your constant isn't found by the compiler.
Solution: With the constant being located in a separate module, you'll need to set it as Public for the other code to see it.
Proof:
In order to prove this theory you can do the following:
Open a new Excel spreadsheet
Go to the VBA designer and add a new module
In this module put:
Const TestString As String = "Test String"
Then add the following code to ThisWorkbook:
Public Sub TestString()
MsgBox (TestString)
End Sub
After adding this return to the workbook and add a button, selecting "TestString" as the macro to run when clicked.
Click the button and a blank message box will appear.
Go back to the VBA designer and change the const in Module1 to Public
Click the button on the spreadsheet and you should now see "Test String" in the message box.
I realize that this question is really old. But for the record I want to document my solutions for the error here: It was a data related error in a spreadsheet! A column was formatted as date and contained a value 3000000. Changing the Format to numbers solved the Error 80004005.