In my VBA project, I frequently make a temporary sheet in the workbook, which gets deleted before the macro exits. The sheet is added as follows
temp = "Temp"
ThisWorkbook.Sheets.Add(after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)).Name = temp
This has been going well for quite a while. Now, however, the code returns an error
Run-time error '1004': Method 'Add' of object 'Sheets' failed
A sheet has been added, although not named "Temp" (instead it's named Sheetn).
I can successfully add a new sheet, but get the following error message. I am unable to change the name of the newly added sheet.
"We couldn't move this sheet"
The workbook is not protected, and there is no other sheet named Temp present in the workbook. Because of this, I feel I have encountered an invisible wall that prevents users from adding large quantities of sheets, even though these sheets are deleted.
This puzzles me, any explanations and/or workarounds?
Having noted from the comment thread that you've solved it by Saving, Closing and Reopening, that #SandPiper has had the same problem recur after a while, and that your OP asks for workarounds, the obvious one that I would suggest would be to stop creating and then removing the Temp sheet, and instead simply create it as a permanent part of the workbook, then hide it, and simply use it when it's needed and clear it afterwards (programmatically).
Having the same problem here and in my case the problem was resolved by temporarily disabling the autosave function. I never had this problem until i started working with 365 version. Any other having this problem on other version then 365?
Microsoft® Excel® voor Microsoft 365 MSO (Versie 2202 Build 16.0.14931.20128) 64 bits
Related
I'm currently using a code to update a file with a loop running through multiple sheets. Up until now, the code ran smoothly. On today's run, I encountered "run-time error '-2147319767 (80028029)' Automation error, Invalid forward reference, or reference to uncompiled type."
The error occurs on the line Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial Paste:=xlPasteValues and presents itself on the 6th iteration of the loop.
I used On Error Resume Next as a temporary measure to complete the run as it was imperative to have it done at that time.
Upon completion, 3 of the iterations had failed (sixth, seventh and tenth). The three had no correlation to one another (i.e. different copy sources, values, etc) but had other iterations with the exact same copy source/values which completed successfully.
Running another copy command at a later time onto these sheets resulted in the same error. I eventually had to delete and recreate the sheet to resolve the error.
' Uploads file update
fpath = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("E3").Value
Workbooks.Open fpath & "Upload.xlsm"
For branchNo = 21 To 37
branchName = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("A" & branchNo).Value
branchGroup = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("B" & branchNo).Value
' Copy/Paste Buy & Sell
Workbooks("TEG Rates.xlsm").Worksheets(branchGroup).Range("D7:G111").Copy
Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial Paste:=xlPasteValues
For no = 7 To 10
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D" & no).Value = "=ROUND(100/C" & no & ",6)"
Next no
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D14").Value = "=ROUND(100/C14,6)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D15").Value = "=ROUND(10000/C15,4)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D16").Value = "=ROUND(100/C16,6)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D19").Value = "=ROUND(100/C19,6)"
Next branchNo
Workbooks("Upload.xlsm").Close SaveChanges:=True
Application.CutCopyMode = False
While currently I am able to operate this code, my concern is that my team will encounter this whilst I'm away. What could have caused this/what can I do to prevent this from occurring? I'd be willing to provide the files if required.
My friend and I had the same issue. I enabled the "AccessibilitycplAdmin 1.0 type admin" under Tools > References (within the VBA editor), that fixed the issue in both computers
I had the same issue with a macro today.
Noticed that the error popped up when selecting a sheet using Sheets(sheet_name_var).Select.
A workaround that I've found is:
- Make a copy of the sheet the macro was having problems with,
- Delete the original sheet,
- Rename the copy to the original name.
Hope this helps.
I was having the same error caused by an issue that was potentially related, and it was helpful to create a worksheet object rather than referencing a sheet within a workbook all in one step. So, instead of:
Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial
You could instead try:
Dim xlWB as Excel.Workbook
Dim xlWS as Excel.Worksheet
Dim xlRange as Excel.Range
Set xlWB = Workbooks("Upload.xlsm")
Set xlWS = xlWB.Worksheets(branchname)
Set xlRange = xlWS.Range("C7")
xlRange.PasteSpecial Paste:=xlPasteValues
Sometimes it's beneficial to break up the steps, even though it is doing the same thing.
The only way I found to solve it was:
Change the property "Load To" for all query results in the damaged Sheet to "Only Create Connection".
Make a copy of the Sheet
Delete the damaged Sheet
Rename the just created Sheet to the name of the damaged one
Change all the query results to the new Sheet in the same original location
I hope this helps.
I had a very similar issue, I have several similar excel files, all with the same code. The code ran in all excels but one, with the same error:
"run-time error '-2147319767 (80028029)' Automation error, Invalid forward reference, or reference to uncompiled type."
I was able to solve the problem by saving the corrupt excel as .xlsx instead of .xlsm, closing all excel applications, reopen the .xlsx, add the code and save as .xlsm. Now it is working...
Exactly same thing happened to me. But with a little bit more serious consequences as my dashboard was already in production.
It was really shocking as code as running smoothly just 5 mins earlier.
Here's the changes that I made -
Conditional formatting
Pivot table updates - major formatting updates
I believe some weird combination of conditional formatting over pivot table might have caused this issue.
One peculiar symptom associated with this corrupted workbook/sheet as that I was unable to see any macro in the dialogue while I was trying to assign a macro to the button.
The dialogue box was empty ! not listing any macros from any module/form/worksheet.
Tried -
Removing pivot table
Resetting formatting
Removing conditional formatting
Restarting excel
Restarting system
None of the above worked !
Next solution, as suggested by Horacio, is to duplicate and delete the corrupted sheet.
This immediately solved the issue.
Similar problem - same error. The sheet is the results of a query "Load To" table. Followed the idea from https://stackoverflow.com/users/13737858/horacio-cano. Changed "Load to" from table to Connection only; deleted the sheet; changed "Load to" to new table; refreshed query. Macro runs without error.
I solved this by removing the reference to Microsoft Scripting Runtime in Tools>References selecting "Ok" and then re-adding it again.
(Not the exactly the same situation as posted by the OP, but the same error message:)
I got the same error message while trying to delete an ActiveX element in a UserForm.
Turns out that I still had (another) user form open as a modal window in the Excel app (which was in the background because I was trying to edit it the Visual Basic Editor).
Simply closing the user form solved the issue.
Not really an answer, but my 2 cents on the matter (a comment could not fit it :))
I found that the underlaying error comes from .NET:
Exception Source: mscorlib
Exception Type: System.Runtime.InteropServices.COMException
Exception Message: Invalid forward reference, or reference to uncompiled type. (Exception from HRESULT: 0x80028029 (TYPE_E_INVALIDSTATE))
Exception Target Site: InvokeDispMethod
With that, I found that this page:
https://developercommunity.visualstudio.com/t/live-code-analysis-causes-compiler-errors-in-code/599442
System.Runtime.InteropServices.COMException : A reference to the component 'MyProjectReference' already exists in the project.
at VSLangProj.References.AddProject(Project pProject)
So it appears the error is linked to some cached file(s) used internally and language stuff.
Now if you look here : What does 'Cor' stand for?
MSCorLib.dll officially became the acronym for Multilanguage Standard
Common Object Runtime Library.
If you finally add in the mix that I was manupulating files in Excel while changing the UI Language in settings just before I got a corrupted file with the same error that the OP mentions, I would guess the error definitely has some thing to do it!...
I have a simple code that runs upon initialization of a userform that sets a few workbook and worksheet variables so they can be used easily throughout the rest of my modules, and the references can be easily changed in one place if the file moves. I recently migrated my workbooks from my desktop to a separate server/drive, and accordingly updated the file pathways; however, when I try to run the code now I immediately get the message:
"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."
This error occurs on the line
Set ReportWkbk = Workbooks("N:\ rest of file pathway here\QuaRT_Template.xlsm")
Is there anything that can be happening on the server/drive that is causing this issue? If so, is there anything I can do to fix it? I do work with other excel workbooks saved in the same location that seem to have no issue being referenced, though their references are in the workbook itself, not through Visual Basic.
The Subscript Out of Range error occurs because the Excel workbook being referenced is not open (or opening) in the same instance of Excel. You can easily reproduce the error by creating two workbooks (name one WorkBook2.xlsx) and ensuring they open in separate instances of Excel. Then run this code:
Sub OpenWkbkNames()
Dim wbk As Workbook
For Each wbk In Workbooks
Debug.Print wbk.Name
Next
'Hmm. Workbook 2 is not listed, but lets activate it and see what happens.
Workbooks("workbook2.xlsx").Activate
End Sub
You could avoid the issue by looping through the names of the workbooks open in THIS instance of Excel to ensure its available.
I've been researching Run-time error '-2147352565 (8002000b)' and found this: https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.vsconstants.disp_e_badindex.aspx
Apparently, that is VS's way of saying Subscript Out of Range too. I suspect (but have no solid proof) that since the code worked locally but the issue appeared after the file was migrated to a shared drive that Windows is taking a long time to open the file so opens it in a new instance of Excel. Essentially, Excel gets impatient and decides to move on while Windows completes its task. I base this assumption on the detection logic that was added to Excel 2013 (https://blogs.office.com/2013/06/03/opening-workbooks-by-running-separate-instances-of-excel/).
I am building a database in Access, for which I import data from an Excel workbook questionnaire. I have coded an Import-sub that selects, opens, retrieves the data from and finally closes the workbook.
The problem is this: for some reason, when I now open any excel workbook on my computer (at a time when neither Access or Excel is in use) some old version of the questionnaire keeps opening as well. This problem doesn't end by restarting the computer, but only by deleting that specific questionnaire-workbook. But then it starts happening with another workbook.
I have a theory that this might be because I - in my import-sub - have opened the questionnaire, encountered a run-time error which has ended the sub before it closed the workbook, and that somehow the workbook is still "open". Or that there still is a link active.
So I have two questions:
1.) Does anyone know how I can fix this problem?
2.) Is there generally any consequences of not closing a workbook that you open through VBA?
My relevant code is:
Dim MyXL As Excel.Application
Dim MyWB As Excel.Workbook
...
in between lots of stuff happening, several times an error occurs which interrupts the program.
...
MyWB.Close False
MyXL.Quit
Appreciate any help on this!
I did Encounter the same Problem and found out that Excel stores the files that open whenever you start Excel in a Folder (XLSTART). The path to mine was: c:\USERS\MyUserName\AppData\Roaming\Microsoft\Excel\XLSTART
As suggested by Ross McConeghy error handling may prevent such an occurrence. But the error already happened and the questionnaire, as you suggested, has placed that workbook in the Folder XLSTART. You have to delete it from that folder to fix the unwanted occurrence.
Your theory is likely. If you never display the Excel application, errors are encountered, and your code never closes the workbook it would be left open in the background and your code would most likely lose reference to it. The next time you open an Excel file the instance of Excel that is already open(but hidden from view) "picks up" the request and opens the file, also displaying the file that was still open from the macro.
1.) You should set up error handling so that the Workbook and Excel application are closed when there is a non-recoverable error.
Sub MySub()
On Error GoTo handle_Err
<... code ...>
Exit Sub
handle_Err:
MyWB.Close False
MyXL.Quit
End Sub
If you have other Error handling statements in your code always reset to On Error GoTo handle_Err instead of GoTo 0 etc.
2.) The only consequences of not closing the Workbook are the obvious ones- the system resources it's using and, if it is open for editing, no one else can edit it.
I had a similar problem and solved it a different way.
I found the connection to an external workbook and fixed it by going to Data > Edit Links.
I am making my first VBA program and trying to run the following function. The function checks a specific named range for the first row which does not have a value greater than it's leading value, but less than 1.
Public Function findPurchase()
Dim CRT As Range
Set CRT = Range("CostRateTable")
Dim existsBetter As Boolean
existsBetter = True
Dim r As Integer
r = 2
Dim c As Integer
c = 4
While existsBetter
Dim Found As Boolean
FoundBetter = False
While Not FoundBetter And c <= CRT.Columns.Count
If CRT(r, c) > CRT(r, 2) And CRT(r, c) < 1 Then
FoundBetter = True
Else
c = c + 1
End If
Wend
existsBetter = FoundBetter
If existsBetter Then
r = r + 1
End If
Wend
findPurchase = CRT(r, 3)
'MsgBox(findPurchase)
End Function
I know the function does what it is supposed to because I have both manually checked the table of values, removed the comment ' from the MsgBox, and used the debug tools to step in and out of each of the functions steps as it went through the table. However, when I reference the function in Excel with =findPurchase() I'm given a #NAME? error. The function even shows up in the function auto-complete box when I begin to type its name. When I write other functions, both with and without parameters, I can reference them just fine, for example:
Function addtwo()
addtwo = 1 + 2
End Function
What am I doing wrong with my function which causes it not to work?
You are getting that error because you have a module with the same name as the function.
Change that name to say find_Purchase and everything will be fine :) See the image below...
I had the same issue myself. It turned out that I "Saved As..." another file and macros were not enabled for that file. No banner on the top appeared, but a #NAME? error was generated.
I reopened the file, enabled macros, and the problem was resolved.
Make sure you have placed the function in a Standard Module. The error message means Excel can't find the function.
When Excel opens an unkown workbook containing VBA-Code, it usually asks for macros to be enabled by the user (depending on the application settings).
If the user then enables the macros, all event-driven procedures will be started, such as auto_open or others.
Custom VBA Functions however require for a full recalculation of the workbook. Otherwise the functions return-value still is #NAME, as the calculation is only done directly after opening the workbook.
In order to work directly at the first time opening, one has to add the following line to the workbook_open event
'
' Workbook open event
Private Sub Workbook_Open()
Application.CalculateFullRebuild
End Sub
Check "Trust access to the VBA project object model" in Macro settings from Macros security
One reason for this problem is security restrictions.. I had this problem and I activate "Enable all macros" from security center, and the problem solved
I had a similar persistent problem with one of my functions when everything else seemed fine.
Open the worksheet & go to the Developer Tab. Open VBA, and back on the Developer ribbon select "View Code". See if it opens any similar Code (apart from your Module) specific to that worksheet (eg. Sheet2 (Code). I found that I had duplicated the code on the worksheet in addition to the Module. Delete the "worksheet" code. (You may need to save the workbook & re-open at this stage). When I deleted the worksheet code, the module function then worked.
In addition to checking some of the above mentioned items, you might need to specify the filename where the custom function is actually defined, e.g. cell content
=XLstart.xlsm!myCustomFunc(Arg1,Arg2)
where myCustomFunc is defined in the startup file XLstart.xlsm.
Following the Excel help for "Correct a #NAME? error":
In the formula bar, select the [suspect] function name.
In the Name Box (to the left of the formula bar), click the arrow and then select a [user-defined] function from the list that Excel suggests.
This will add the filename per the above format.
MS 2010, Windows 10.
Here's why I got that error. This answer is not provided so far.
If you have two or more workbooks (spreadsheets) open, then you may have your module under the other workbook - not the only you want to do the calculation on. This may seem impossible but ... as soon as you open the Developer/VBA code editor Excel wants to show you the structure (objects, modules, etc) of every open workbook. It's not what I expect as a developer, but there it is. So like me, you may have pressed 'Add module' and dropped the code in another workbook and worksheet.
If this is your issue, nothing mention above will work. Move your VBA module and code to the correct spreadsheet visible through this VBA code editor.
True,
I had the same (in Excel 2010) and when I migrated to Excel 2016 , the function prototype was shown, but when I completed the function, the #NAME error was shown with a pop-up... so the code was never triggered.
It turned out I had a Macro of the same name as a Sub or UDF function !
I renamed the Macro, and then it worked
Cheers
Another cause I found for the #NAME? error is that the macro workbook with the custom function has a range name the same as the function name. I changed the function name and solved the problem.
This solution applies to users with an Excel installed in another language than "United States English":
I had a similar problem when making a copy of the active workbook to duplicate it and immediately opened the copy afterwards:
Non-working code:
ThisWorkbook.SaveCopyAs NewFileName
Set wb = Workbooks.Open(FileName:=NewFileName)
This always showed me several cells with Error 2029 / "#NAME?". If I opened the Workbook "the official way" via the File-Menu it worked as expected.
I solved the issue by adding the parameter "local:=true" to the open statement:
Working code:
ThisWorkbook.SaveCopyAs NewFileName
Set wb = Workbooks.Open(FileName:=NewFileName, Local:=True)
as VBA expected english function names in my German workbook. With this parameter VBA is told directly to use the local names.
I hope that helps someone not to loose several hours, as I did...
Short answer - if the function was working before, RESTART YOUR COMPUTER.
Long answer - I had this same thing happen to me. The problem is that the function I had created had been working for months. Then one day it just started showing a #NAME error instead of working like it was before. I had tried closing all other excel workbooks and even closing excel all-together and re-opening the sheet. Nothing seemed to work. Then for kicks, I edited the code to where I knew VBA would complain that there is a compile error. Surprisingly, it didn't complain. OK... I saved and closed excel anyways and then restarted my computer.
Once rebooted, I re-opened the excel workbook. Then VBA finally gave me a compile error. So I changed my function back to the original code I had before and now the sheet is running the function like it is supposed to. No more #NAME error.
Not sure all of those steps are necessary, but simply restarting the computer seems to have fixed my issue.
I have an old workbook (made by someone years ago) with a few worksheets in it. When I open this workbook, Excel complains with messages like 'Cannot find ActivateWorksheet', 'Cannot find DeActivateWorksheet'.
There are no event handlers in the code. I want to avoid getting these messages from Excel but could not find how to reset them. I checked the OnSheetActivate, OnSheetDeactivate etc properties to see if some macro is assigned but found them to be empty.
Is there any other place where I can check and remove these handlers?
It might be related to AddIns - do you have all the necessary AddIns installed?
There's one more place to look: NamedRanges. I found that the worksheet has Names defined with values such as "=ActivateWorksheet", "=DeActivateWorksheet" but these macros were nowhere. When a worksheet is activated, the Names on that sheet is refreshed (or recalculated) and i my case the macro were being called.