Error: Can't move focus because it is invisible - excel

I have the following code that works in all other circumstances except in a single where it returns the error Can't move focus because it is invisible, not enable, or type that does not accept focus. The data in sheet consists only basic numbers and words. My objective is to select a range from one work book and paste it to another. It appear that excel does not recognise anything to be in the cells, although there in fact is. Does anyone know why this may be happening?
Set Users = Application.Workbooks.Open(PathA)
With Prices
.Sheets("Sheet").Range("A:AJ").Select
Selection.Copy
End With
'Set Risk = Application.Workbooks.Open(PathX)
With Risk
.Sheets("Sheet").Range("A1:AJ1048576").PasteSpecial Paste:=xlPasteAll
.Save
' .Close
End With
Users.Close

it looks like someone else had the same issue and was able to resolve it on an MSDN forum
http://social.msdn.microsoft.com/Forums/office/en-US/3263b079-7e4f-452c-8dcc-92c682b8370b/excel-form-cant-move-focus-to-the-control-because-it-is-invisible-not-enabled-or-of-a-type-that?forum=exceldev
maybe this fix will apply to your situation too.
... OK so on that page, one guy has a kludge that seemed to work for him:
Error was:
Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus.
How to Fix
1. Select the object with the problem, e.g. the Form or Control.
2. In the properties windows, select the name of the object and rename adding an "x" to the end, e.g. Rename CPanel to CPanelx.
3. Save the Form.
4.Now rename the CPanelx back to CPanel.
5. Run your form.
6. Problem solved.
Something screwy with Excel VBA, not sure what !, but this will get you working again.
Steve D.
and then someone else described the underlying problem, but his solution involved using design mode, which seems like it is maybe defeating the purpose of automating in vba, but the moderator seemed to like his answer better, so here that is as well
In normal use activeX controls are intended only to be activated, not selected, there's a difference. If you partifcularly want to Select the control (manually or with code), try putting Excel into Design mode first.
See also the topic "Why can't I select form and ActiveX controls?" in Excel's help (not VBA's help)
Peter Thornton

"Run-time error '-2147352565 (8002000b)': Can't move focus to the control because it is invisible, not enabled or of a type that does not accept the focus" Can be overcome but sequentially defining the area you wish to select. Obviously some may do this in any case, but it this specific instance it is needed to overcome the issue. This is an example for copying from one workbook to another and pasting where U is the sheet excel finds to be "invisible".
Dim U As Workbook
Dim Us As Worksheet
Set U = Application.Workbooks.Open(Path)
Set Us = U.Worksheets("sheet")
With Us
.Range("A:AJ").Select
Selection.Copy
End With
U.Close SaveChanges = True
With DestinationWorkbook
.Sheets("sheet").Range("A:AJ").PasteSpecial Paste:=xlPasteAll
.Save
End With

Just to help in case you didn't find the answer till now :
In my case this message came out when I redimensioned the application window while it was maximized :
e.g. Application.width = 100 (on Excel 2003 or 2007)
The solution in this case, is to first bring the application window to NORMAL.
e.g. ActiveWindow.WindowState = xlNormal

Related

Copying Editable Excel chart to Word Error 4605

I have a macro that is intended to copy a chart from excel into a word document in the same way as manually copy and pasting using "Keep Source Formatting and Embed Workbook." Below is the code that, to my understanding, should accomplish this.
Set reductionChart = graphWorksheet.ChartObjects("reduction")
reductionChart.Copy
masterReport.Paragraphs.Last.Range.PasteAndFormat wdChart
graphWorksheet is the worksheet that contains the graphs, masterReport is the word document.
The issue I am having is error 4605 command not available on the PasteAndFormat line. I happened to discover that manually copying the graph then running the line worked without issue. Thinking that maybe right clicking copied in a different way than .copy so I record a macro of the action and ended up with:
ActiveSheet.ChartObjects("Reduction").Activate
ActiveChart.ChartArea.Copy
Even substituting this in the error still occurs. What is happening here?
After some additional testing I am thinking that possibly when using .copy the chart is sort of only stored within excel and not the clipboard so when paste and format looks for something it see an empty clipboard and has an error, but right clicking copy stores it to the clipboard hence why is available still even after I run ActiveChart.ChartArea.Copy again.
I've attempted to create new workbook with a single sheet and chart. Also tried using late binding instead on the off chance that did something. This is the full code still giving the same issue
Sub test()
Dim masterWord As Object
Dim masterReport As Object
Set masterWord = CreateObject("Word.Application")
Set masterReport = masterWord.Documents.Add
masterWord.Visible = True
ThisWorkbook.Worksheets(1).ChartObjects("Chart 1").Copy
masterReport.Paragraphs.last.Range.PasteAndFormat wdChart
End Sub
After much testing this is the best workaround I'm managed to figure out.
reductionChart.Chart.ChartArea.Copy
masterReport.Paragraphs.Last.Range.PasteAndFormat wdFormatOriginalFormatting
masterReport.InlineShapes(masterReport.InlineShapes.Count).LinkFormat.BreakLink
wdFormatOriginalFormatting and wdPasteDefault both work and don't seem to make a difference to the outcome as far as I have seen.
This has one issue that I've found which is that on ActiveDocument.Fields.Update an information box will popup warning that the linked file is unavailable. This will occur for each unlinked item. I attempted to use Application.DisplayAlerts = False but this did not prevent the popup. This may come back to bite me, but I simply removed this line as it was unnecessary for my purposes.

How to fix run time error 400 which occurs only in shared mode of excel via VBA code

I really don't know what causes error 400.
Below code runs perfectly fine in normal mode but as soon as i enable my excel in sharing mode and tries to user form, it gives me VBA 400.
What i am trying to do here is to change shape's text and disable its OnAction event, once user form is shown to user. so that another user accessing same file will come to know that someone is using "User Form" to enter data.
Dim shp As Shape
For Each shp In ActiveSheet.Shapes
If shp.TextEffect.Text = "Sort Customer" Then
shp.OnAction = ""
shp.TextEffect.Text = "Wait!!!"
End If
Next
Q. Is there any way to publish changes made by any user in shared excel automatically.
I suspect that your code falls in one of the numerous limitations of Excel shared mode, described here (see unsupported features), including
Using a data form to add new data
Using drawing tools
Inserting or changing pictures or other objects
(Please note that, due to its format, I could not easily copy that list of unsupported features in my answer.)
As far as I know, in order to keep the changes you should choose if the first one who introduces the data rules or you will choose in case of conflict. As you are looking for an "automatic" way, you should chose the first one.
You can find a good explanation described here
At Review > Share Workbook , Advanced Tab. At "Conflicting changes between users", you should chose "The changes being saved win". So as the data are introduced and saved, they are reflected.
Hope it helps.
Create a vba function in the sheet (NOT A MODULE) where users can activate the user form:
insert the following function there:
Function HyperlinkClick()
'source: https://stackoverflow.com/a/33114213/11971785
Set HyperlinkClick = Range("B2")
If HyperlinkClick.Value = "Sort Customer" Then
'sets info on WAIT
HyperlinkClick.Value = "WAIT!!!"
'shows userform
UserForm1.Show
Else
'sets info back to normal value
HyperlinkClick.Value = "Sort Customer"
End If
End Function
In the user form you can add an userform_terminate Event, which automatically changes the value in B2 back (I guess you could also do that for an workbook Close Event be on the safe side).
Private Sub userform_terminate()
'Code goes here
Range("B2").Value = "Sort Customer"
End Sub
In Excel now create a "Frontend" such as this:
and add the formula:
=HYPERLINK("#HyperlinkClick()";"Click")
to the cell where a user needs to click to open the UserForm (in this case to D2).
If you now share the workbook and click on "Click" in D2 an Event is triggered and the VBA Function "HyperlinkClick()" is called. In this function you can essentially do anything now.
Explaination:
Instead of using a graphic, button etc. which will not work correctly in shared mode, we can simply use links (which work) to trigger an Event.
Instead of "creating" and "deleting" Hyperlinks (which also does not work in shared mode) we simply build dynamic links which Point to userform.show or to nothing, depending of the situation.
Error 400 Problem: Should be solved by skipping the modify object part of the code.
Multiple User Problem: Should be solved, since only one user can activate the userform.
Is there any way to publish changes made by any user in shared excel automatically.: I guess so, please provide more information on what exactly you want to achive (incl. example).
Tip:
In General you might want to check out MS Access since it has as default feature multi-user Access and users there can use the same form at the same time, since the users only get exclusive Access for specific datapoints not the whole table/workbook or file.

Excel VBA forcing selection of objects after run

I've researched this to death and feel like I'm the only person it's ever happened to.
I have some VBA that:
Creates a copy of 3 sheets to a new wb
In the new wb converts to values, deletes objects (shapes and controls) and all but 3 ranges
Opens an existing third file and sets the contents of three ranges in that to match the new wb
Closes the existing file (saved)
Closes the new wb (saved)
Gives a message box saying complete
At the end of all this, something weird happens with the state of the windows. The selected cell does not appear selected. If I try and click a control afterwards, it selects the object (hence users could drag them). It shouldn't and this is the big problem.
I've tried selecting a cell through code, it throws an error. I had limited success by forcing drawing mode off using Call CommandBars("Drawing").Controls("Select Objects").Execute and activating a specific sheet & selecting a cell. However, even then if I even click on a few cells afterwards, the next time I select a control it will select it as an object rather than click the thing.
I have no idea why and can't find anyone who's seen this before.
Any ideas on what I can do?
Thanks,
Basil
I didn't figure it out entirely, but I did find a fix. Hopefully it works for anyone else who finds this problem.
At the end of the code I added this:
ActiveSheet.Shapes.Range("ctrlExportPrices").Select
ActiveSheet.Range("B8").Select
So it forced a control on the sheet to be selected, and then a cell.
The next time I select the control manually, it clicks it rather than selecting the drawing object.

Copy Excel formulas from one workbook to another using VBA and maintaining the names that already exist

I'm using this code to copy formulas from one workbook to another.
For Each r In templateWbk.Sheets("BSC").Cells.SpecialCells(xlCellTypeFormulas)
addressRange = r.Address
r.Copy instanceWbk.Sheets("BSC").Range(addressRange)
Next
Occationally I get a popup that says "The name "xxxxx" already exists. Click Yes to use that version of the name, or click No to rename the version of "xxxxx" you're moving or copying.
I don't want this popup to appear. I always want the exact content of the cells to be copied and nothing more, in other words I want to use the existing version of the name. This is the major thing I need help with.
The code is also rather slow as the sheets have many formulas. So if you can suggest a faster approach I would be thankful for that as well.
Could you simply set the value in one workbook to equal the value in the other? This would keep eliminate the "copy" method:
For Each r In templateWbk.Sheets("BSC").Cells.SpecialCells(xlCellTypeFormulas)
instanceWbk.Sheets("BSC").Range(r.Address).Formula _
= templateWbk.Sheets("BSC").Range(r.Address).Formula
Next
Also, you may try to change the DisplayAlerts property:
Application.DisplayAlerts = False
Untested for your scenario, but a good way to get rid of many popups.

Excel VBA can't open Workbook

First: I'm using Excel 2007, but the code has to work for Excel 2003 as well.
My problem is the following: I need to access cells in a different workbook, which may be closed. The following code can be found all around the web:
Function Foo()
Dim cell As Range
Dim wbk As Workbook
Set wbk = Workbooks.Open("correct absolute path")
' wbk is Nothing here so the next statement fails.
Set cell = wbk.Worksheets("Sheet1").Range("A1")
Foo = cell.Value
wbk.Close
End Function
sadly, wbk is Nothing after the open statement (I'd love to give a better error message, but no idea how I'd do that; what I'd give for a real IDE and an useful language :/). The absolute path is correct and points to a valid excel xlsx file.
Also I assume the best way to do this, is to "cache" the workbook and not open/close it every time the function is called? Any possible problems with that (apart from having to handle the situation when the workbook is already open obviously)?
Image while stepping through:
I can reproduce this problem. It only happens to me when I attempt to paste this code into a user-defined function.
I believe this is by design (the quote is for XL 2003, but the same thing happens to me on XL 2010)
Using VBA keywords in custom functions
The number of VBA keywords you can use in custom functions is smaller than the number you can use in macros. Custom functions are not allowed to do anything other than return a value to a formula in a worksheet or to an expression used in another VBA macro or function. For example, custom functions cannot resize windows, edit a formula in a cell, or change the font, color, or pattern options for the text in a cell. If you include "action" code of this kind in a function procedure, the function returns the #VALUE! error.
http://office.microsoft.com/en-us/excel-help/creating-custom-functions-HA001111701.aspx
The only workaround I've found is to call this kind of code via a normal macro. Something like selecting the cells to apply it to, then looping over Selection or the like.
You can use this (similar to what Bruno Leite proposed, but much simpler to write):
Dim excelApp As New Excel.Application
excelApp.Visible = False
Set WB = excelApp.Workbooks.Open(FileName, xlUpdateLinksNever, True)
As UDFs are called repeatedly, you should make sure to do an excelApp.Quit before exiting the function (and a WB.close(False) before) to avoid having countless Excel instances running on your box.
I spent some thoughts on it and came to the conclusion that you cannot mess around with the workbooks of the current instance of excel while executing a UDF. On the other hand, opening a second instance of excel will do the job without interference.
To get data from Workbook without is open, you can use this, with ADO connection.
To use in Excel 2007 change this
Microsoft.Jet.OLEDB.4.0
to
Provider=Microsoft.ACE.OLEDB.12.0
and
Extended Properties=\"Excel 8.0;HDR=Yes;\
to
Extended Properties=\"Excel 12.0;HDR=Yes;\
[]'s
The workaround of putting my routine into a separate macro in the workbook module, and calling that macro from the Workbook_BeforeSave code, seems to have done the trick.
I've had a similar issue, but in my case it's a "Workbooks.Open(filename)" command at the start of a small routine embedded in Workbook_BeforeSave. VBA just skips right over the line of code as if it weren't there, it doesn't even report an Err.Code or Err.Description.
The only clue for me was that it's part of the Workbook_BeforeSave routine, and the limits with Functions above seem to indicate that could be a possible cause. So I dug around further to find more details.
It seems that Workbook_BeforeSave disables Excel from opening more files, and I guess there's a good reason for doing that, since the File > Open option is still visible in the File menu, but it can't be clicked. Strangely, the Open toolbar icon/button still works, and so whilst I can manually open the file from there, I wonder if it's because it's impossible to call this action from VBA code and that's why they allowed it?
You don't have to "Set" a cell, It's part of the workbook class (as far as I know). Just use the following...
foo = wbk.Worksheets("Sheet1").Range("A1").Value
I would suggest that you open you the new workbook upon opening the calling workbook, in the worbook_open event.
You then store the new workbook reference in a global variable.
Then the function called by your cell uses the said global variable instead of trying to open a new workbook. This way you go around the limitations.
PS : Of course global variable are to be avoided, some sort of container would be better than a direct global variable.
You can check the error in a proper way by using the following code:
filelocation = c:\whatever\file.xlsx
On Error GoTo Handler 'this is key as if the next row returns an error while opening the file it will jump to the Handler down there.
Set wkb2 = Workbooks.Open(filelocation, ReadOnly)
Handler:
MsgBox "File " & filelocation & " does not exist or cannot be reached, please review and try again"
I know that this does not answer the question (that's why I also landed in this thread, as I cannot open the file and can't understand why is that so)
Cheers,
RV

Resources