Getting error when attempting to remove hidden names in excel - excel

I'm trying to run a macro to clear my workbook of hidden names so when a tab is copied I don't have to hold down enter for 5 minutes because of all of the hidden names.
I looked around for some VBA code to accomplish this but am getting the error:
"Run-time error '1004': The syntax of this name isn't correct."
I assume it's running into an invalid name so it can't delete it?
Code below:
Sub Remove_Hidden_Names()
Dim xName As Variant
If MsgBox("Do you really want to delete all hidden names in this workbook?", vbQuestion + vbYesNoCancel, "Delete hidden names?") = vbYes Then
For Each xName In ActiveWorkbook.Names
If xName.Visible = False Then
xName.Delete
End If
Next xName
MsgBox "All hidden names in this workbook have been deleted.", vbInformation + vbOKOnly, "Hidden names deleted"
End If
End Sub

Seems like there might be an invalid or corrupted name, the box shouldn't allow for dashe or hyphens. You could try to open the XML of the worksheet, find the invalid name and change it to a valid one.

Related

I'm using a function to delete all the names in vba but I have an error 1004

I got this piece of code from https://www.extendoffice.com/
Sub DeleteNames()
'Update 20140314
Dim xName As Name
For Each xName In Application.ActiveWorkbook.Names
xName.Delete
Next
End Sub
But when I try to run it give me an error 1004 (syntax of this name is incorrect) on the line xName.Delete
The error is that it try to delete "hidden" internal Name ranges that start with a _xlfn which I cannot remove. so I use a Split to check if it starts with _xlfn and if it don't, then it means I can delete it.
Sub DeleteNames()
Dim xName As Name
For Each xName In Application.ActiveWorkbook.Names
If Split(xName.Name, ".")(0) <> "_xlfn" Then
xName.Delete
End If
Next
End Sub
The problem comes from internal Names that are issued from Excel and start with an underscore. As far as I know, all those names start with _xlfn. They are a hint that an Excel file was created with a newer version of Excel and then opened with an older version that doesn't support some features (eg functions in a formula), see for example here
Those Names cannot be deleted. I guess the error message is a little misleading, it would be better if there would be a message like "this object cannot be deleted.". Anyhow, the workaround is easy, either check the name of that Name or enclose the
deletion with an error handler:
For Each xName In Application.ActiveWorkbook.Names
if left(xName.Name, 1) <> "_" Then xName.Delete
Next
Or
For Each xName In Application.ActiveWorkbook.Names
On Error Resume Next
xName.Delete
On Error Goto 0
Next

How to clear contents of an Excel Workbook through vba

I am trying to automate data with a master wookbook. When I open the workbook I want a msg box to appear and clear the contents of specific columns in tables in one of the worksheets. I keep getting the "Application-defined or object-defined error". This is the code in my "This workbook" section:
Option Explicit
Sub Workbook_Open()
Dim answer As Integer
answer = MsgBox("Do you want to clear the totals?", vbYesNo + vbQuestion, "Clear Totals")
If answer = vbYes Then
Call Sheet1.ClearContents_1
End If
End Sub
This is my Sheet1 code:
Sub ClearContents_1()
Call Loop_Clear_C
Call Loop_Clear_M
Call Clear_S
End Sub
Sub Loop_Clear_C()
For i = 1 To Range("UserTable79").Rows.Count
Range("UserTable79[Total]")(i) = 0
Next i
End Sub
Sub Loop_Clear_M()
For i = 1 To Range("ServiceTable79").Rows.Count
Range("ServiceTable79[Total]")(i) = 0
Next i
End Sub
Sub Clear_S()
Range("TotalTable79[Actual Total]").ClearContents
End Sub
They worked separately but not together. The msg box comes up but doesn't run the Sheet1 code. How do I call upon this sheet code?
Edit: The Sheet1 code no longer works either.
Often the "Application-defined or object-defined error" message comes up when the range that you're referring to doesn't exist. If you click on Sheet1 to activate it and then try to use the Immediate panel to perform an operation on the ranges you're referring to (e.g. try entering Range("UserTable79").Select) do you get an error?
Explicitly specifying the worksheet when calling the function from the "ThisWorkbook" section (e.g. if the worksheet is named "SheetName" then specifying Call ThisWorkbook.Sheets("SheetName").ClearContents_1 rather than Call Sheet1.ClearContents_1) can help.
Also - note that you can clear the entire table ranges or entire columns in Loop_Clear_C and Loop_Clear_M with ClearContents or EntireColumn.ClearContents if that's easier.

Stopping a sub when the required text isn't found

I am currently linking lots of subs together to format headings in excel for upload to other dashboard software. The headings need to be in a certain order. I am running several subs triggered by a command button to search for the heading text in a sepcified range of cells. having trouble with if the heading isn't found which sometimes happens as the data is downloaded from brandwatch and if nothing returns for that particular subject in Brandwatch then the heading isn't in the downloaded data file. I want the macro to stop when the required text isn't found in the range.
I am only just learning VB and have no idea how to stop the next sub from running if the specific text isnt found. As it stands at the minute it is putting in another heading as the next subroutine is a copy active column and then goto another specific column and paste.
The message 'The Value you are searching for is not available' comes up but then the next sub pastes the wrong heading in when I just want all the macros to stop at that point.
Any help would be greatly appreciated.
Thanks Sylly
the offending Subroutine is below
Sub FIND_POTENTIAL_IRRELEVANT_MENTIONS()
'============================
'FIND POTENTIAL_IRRELEVANT_MENTIONS
'============================
Dim MyValue As Variant
On Error Resume Next
Range("CT9:HD9").Find(What:="Market Insight Report").Select
On Error GoTo 0
MyValue = ActiveCell.Value
If MyValue = "" Then
MsgBox "The Value you are searching for is not available"
Else
MsgBox MyValue & " found in " & ActiveCell.Address
End If
End Sub

Put VBA into wait mode while the user edits sheet in other workbook opened by VBA

I am trying to achieve the following:
I have a workbook that whose job is to loop through a set of input files (from different departments), all of which are supposed to be identical. However, i have noticed that some departments tend to rename their sheets at will. I have code that loops through all files and checks whether a given sheet named "Template" is there or not.
Now, i have a long time to plan for this, but once the input from departments start pouring in, i have very little time to verify everything and import it. One such thing is to implement a "fix errors" function, which, among other things, checks for the presence of the "Template" sheet in the workbook. If it is not there, i want the macro to open the workbook, allow the user (me) to find the correct sheet, manually rename it to "Template", and then save and close. Only then do I want the code to continue to run (checking the next workbook or other errors in this same workbook), in a similar way that happens when a mesage box or file dialog opens.
I have the following for this function for now (part of a larger code, project is a custom class):
If Not project.FileHasSheet Then
answer = MsgBox("Open file and add sheet?", vbYesNo + vbQuestion)
If answer = vbYes Then
Set tempWorkbook = Workbooks.Open(ThisWorkbook.Path & "/Inputfiler/" & project.filename)
MsgBox ("done")
tempWorkbook.Close
Else
'do something
End If
The messagebox "done" is going to be removed once this works. The code above just opens the workbook and immediately closes it.
If Not project.FileHasSheet Then
answer = MsgBox("Open file and add sheet?", vbYesNo + vbQuestion)
If answer = vbYes Then
Set tempWorkbook = Workbooks.Open(ThisWorkbook.Path & "/Inputfiler/" & project.filename)
Do Until IsFileOpen(ThisWorkbook.Path & "/Inputfiler/" & project.filename) = False
DoEvents
Loop
MsgBox ("done")
tempWorkbook.Close
Else
'do something
End If
This does not work either. The other workbook opens and the "hourglass" starts spinning, not allowing the user to edit the newly opened workbook.
The IsFileOpen function is:
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
Case Else
Error errnum
End Select
End Function

Macro to go to a worksheet [duplicate]

This question already has an answer here:
Excel Find a sheet based on name
(1 answer)
Closed 8 years ago.
I have an excel workbook with a lot of sheet tabs, and to make navigating it easier for user's I've added a macro to bring up an input box so that they can type in the sheet they want to go to.
It works but the problem is that if they type in a sheet name incorrectly it does nothing, the input box goes away, and the user is left on the same sheet they were already on. What I would like it to do is if a user types in a sheet name that doesn't exist for it to bring up a box with a list of all the tabs and allow them to choose from the list. Barring that, at least a message box informing them they entered a non-existent sheet name and to try again, and to then go back to the input box rather than it disappearing. Here's the code I've been working with so far-
If that's not possible, I'd rather have it just bring up a list of available sheets in the first place and forget the input box altogether. My thought was that it would be nice to type in the needed sheet rather than having to sort through the list every time, but it'd be preferable to nothing happening.
Sub GotoSheet()
Dim sSheet As String
sSheet = InputBox( _
Prompt:="Sheet name or number?", _
Title:="Input Sheet")
On Error Resume Next
If Val(sSheet) > 0 Then
Worksheets(Val(sSheet)).Activate
Else
Worksheets(sSheet).Activate
End If
End Sub
If you would like a list of available sheets to pop up so you can choose one just make a quick UserForm, insert a ListBox (a ComboBox would work as well, I prefer a ListBox visually), and have it populate on userform_initialize:
Private Sub UserForm_Initialize()
Dim WS As Worksheet
For Each WS In Worksheets
ListBox1.AddItem WS.Name
Next WS
End Sub
Make sure the MultiSelect property is set to 0 for single select then create an ok button that goes to the selected sheet:
Private Sub CommandButton1_Click()
Sheets(ListBox1.Value).Activate
Unload Me
End Sub
Then create a button or whatever to show the form.
I believe the root of your problem at the moment is On Error Resume Next. This is causing the sub to simply exit when your else statement encounters an error, such as the sheet does not exist. Instead you need to handle that error through the use of something like On Error GoTo. As in:
Sub GotoSheet()
Dim sSheet As String
sSheet = InputBox( _
Prompt:="Sheet name or number?", _
Title:="Input Sheet")
On Error GoTo noSheet
If Val(sSheet) > 0 Then
Worksheets(Val(sSheet)).Activate
Exit Sub
Else
Worksheets(sSheet).Activate
Exit Sub
End If
noSheet:
'Enter your code to display a warning that the sheet does not exist
'and/or bring up a selection box of all sheets
End Sub
Here is some more information on the On Error statement, which may be of use: https://msdn.microsoft.com/en-us/library/aa266173%28v=vs.60%29.aspx
This will do it for you and handles all error without the need to use On Error statement.
Function Validate(SheetName As String) As Boolean
For i = 1 To ThisWorkbook.Worksheets.Count
If SheetName = ThisWorkbook.Worksheets(i).Name Then
Validate = True
Exit Function
Else
Validate = False
End If
Next
End Function
Sub GotoSheet()
Dim sSheet As String
sSheet = InputBox( _
Prompt:="Sheet name or number?", _
Title:="Input Sheet")
Do While Validate(sSheet) = False
'This if statement is true when the user click cancel or x button
If sSheet = "" Then
Exit Do
End If
MsgBox (sSheet & " does not exist. Please enter a valid sheet name.")
sSheet = InputBox( _
Prompt:="Sheet name or number?", _
Title:="Input Sheet")
Loop
If sSheet <> "" Then
Worksheets(sSheet).Activate
End If
End Sub

Resources