I have just experienced the same problem. After some trial-and-error I discovered that if the selection was to the right of my filter area AND the number of shown records was zero, ShowAllData would fail.
A little more context is probably relevant. I have a number of sheets, each with a filter. I would like to set up some standard filters on all sheets, therefore I use some VBA like this
Sheets("Server").Select
col = Range("1:1").Find("In Selected SLA").Column
ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=col, Criteria1:="TRUE"
This code will adjust the filter on the column with heading «In Selected SLA», and leave all other filters unchanged. This has the unfortunate side effect that I can create a filter that shows zero records. This is not possible using the UI alone.
To avoid that situation, I would like to reset all filters before I apply the filtering above. My reset code looked like this
Sheets("Server").Select
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
Note how I did not move the selected cell. If the selection was to the right, it would not remove filters, thus letting the filter code build a zero-row filter. The second time the code is run (on a zero-row filter) ShowAllData will fail.
The workaround is simple: Move the selection inside the filter columns before calling ShowAllData
Application.Goto (Sheets("Server").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
This was on Excel version 14.0.7128.5000 (32-bit) = Office 2010
Я только что испытал ту же проблему. После некоторой пробной ошибки я обнаружил, что если выбор был справа от моей области фильтра. И количество показанных записей было равно нулю, ShowAllData потерпит неудачу.
Возможно, немного больше контекста. У меня есть несколько листов, каждый с фильтром. Я хотел бы установить некоторые стандартные фильтры на всех листах, поэтому я использую некоторые VBA, подобные этому
Sheets("Server").Select
col = Range("1:1").Find("In Selected SLA").Column
ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=col, Criteria1:="TRUE"
Этот код будет настраивать фильтр в столбце с заголовком «В выбранном SLA» и оставить все остальные фильтры без изменений. У этого есть неудачный побочный эффект, который я могу создать фильтр, который показывает нулевые записи. Это невозможно, используя только пользовательский интерфейс.
Чтобы избежать этой ситуации, я хотел бы, чтобы reset все фильтры, прежде чем применять фильтрацию выше. Мой код reset выглядел так:
Sheets("Server").Select
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
Обратите внимание, что я не перемещал выбранную ячейку. Если выбор был справа, он не удалял фильтры, таким образом, чтобы код фильтра создавал фильтр с нулевой строкой. Во второй раз, когда код запускается (в фильтре с нулевой строкой) ShowAllData завершится с ошибкой.
Обходной путь прост: переместите выделение внутри столбцов фильтра перед вызовом ShowAllDatap >
Application.Goto (Sheets("Server").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
Это было в Excel версии 14.0.7128.5000 (32-разрядная версия) = Office 2010
- Remove From My Forums
-
Question
-
Hi Folks,
What is the proper way to trap an error on the command
ActiveSheet.ShowAllData
This command is the equivalent of Data, Sort & Filter (group), Clear. This command clears all filters on a filtered range on a sheet. But if none of the filters have any conditions set this command errors out. The uninformative
message is «ShowAllData method of worksheet class failed».It may be that
On Error Resume Next
ActiveSheet.ShowAllData
On Error Go To 0
Is the correct way but maybe not?
TIA,
Shane
If this answer solves your problem, please check Mark as Answered. If this answer helps, please click the Vote as Helpful button. Cheers, Shane Devenshire
Answers
-
You can test whether the FilterMode property of the sheet is True:
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData End If
Regards, Hans Vogelaar
-
Marked as answer by
Wednesday, March 21, 2012 5:28 PM
-
Marked as answer by
I notice my VBA script doesn’t work when there’s an autofilter already on. Any idea why this is?
wbk.Activate
Set Criteria = Sheets("Sheet1").Cells(i, 1)
Set rng = Sheets("Sheet1").Range(Cells(i, 2), Cells(i, 4))
wb.Activate
If ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData 'remove autofilter, but it crashes on this line
Selection.AutoFilter
Range("$A$1:$BM$204").AutoFilter Field:=2, Criteria1:=Criteria.Value
rng.Copy
Range("$BC$2:$BE$204").SpecialCells(xlCellTypeVisible).PasteSpecial
Many thanks
This question is related to
excel
vba
autofilter
The answer is
AutoFilterMode will be True if engaged, regardless of whether there is actually a filter applied to a specific column or not. When this happens, ActiveSheet.ShowAllData
will still run, throwing an error (because there is no actual filtering).
I had the same issue and got it working with
If (ActiveSheet.AutoFilterMode And ActiveSheet.FilterMode) Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
This seems to prevent ShowAllData from running when there is no actual filter applied but with AutoFilterMode turned on.
The second catch Or ActiveSheet.FilterMode
should catch advanced filters
The simple way to avoid this is not to use the worksheet method ShowAllData
Autofilter has the same ShowAllData method which doesn’t throw an error when the filter is enabled but no filter is set
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData
The error ShowAllData method of Worksheet class failed
usually occurs when you try to remove an applied filter when there is not one applied.
I am not certain if you are trying to remove the whole AutoFilter
, or just remove any applied filter, but there are different approaches for each.
To remove an applied filter but leave AutoFilter
on:
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
The rationale behind the above code is to test that there is an AutoFilter
or whether a filter has been applied (this will also remove advanced filters).
To completely remove the AutoFilter
:
ActiveSheet.AutoFilterMode = False
In the above case, you are simply disabling the AutoFilter
completely.
I have just experienced the same problem. After some trial-and-error I discovered that if the selection was to the right of my filter area AND the number of shown records was zero, ShowAllData would fail.
A little more context is probably relevant. I have a number of sheets, each with a filter. I would like to set up some standard filters on all sheets, therefore I use some VBA like this
Sheets("Server").Select
col = Range("1:1").Find("In Selected SLA").Column
ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=col, Criteria1:="TRUE"
This code will adjust the filter on the column with heading «In Selected SLA», and leave all other filters unchanged. This has the unfortunate side effect that I can create a filter that shows zero records. This is not possible using the UI alone.
To avoid that situation, I would like to reset all filters before I apply the filtering above. My reset code looked like this
Sheets("Server").Select
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
Note how I did not move the selected cell. If the selection was to the right, it would not remove filters, thus letting the filter code build a zero-row filter. The second time the code is run (on a zero-row filter) ShowAllData will fail.
The workaround is simple: Move the selection inside the filter columns before calling ShowAllData
Application.Goto (Sheets("Server").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
This was on Excel version 14.0.7128.5000 (32-bit) = Office 2010
I am also the same problem. I think the reason are,
1) When my activecell is within the table, «ActiveSheet.ShowAllData» can be work.
2) When my activecell not within the table,
«ActiveSheet.ShowAllData» cannot work.Using this code, ActiveSheet.ListObjects(«Srv»).Range.AutoFilter Field:=1 can clear the filter.
This will work. Define this, then call it from when you need it. (Good for button logic if you are making a clear button):
Sub ResetFilters()
On Error Resume Next
ActiveSheet.ShowAllData
End Sub
Add this code below. Once turns it off, releases the filter. Second time turns it back on without filters.
Not very elegant, but served my purpose.
ActiveSheet.ListObjects("MyTable").Range.AutoFilter
'then call it again?
ActiveSheet.ListObjects("MyTable").Range.AutoFilter
Я замечаю, что мой VBA script не работает, когда уже установлен автофильтр. Любая идея, почему это?
wbk.Activate
Set Criteria = Sheets("Sheet1").Cells(i, 1)
Set rng = Sheets("Sheet1").Range(Cells(i, 2), Cells(i, 4))
wb.Activate
If ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData 'remove autofilter, but it crashes on this line
Selection.AutoFilter
Range("$A$1:$BM$204").AutoFilter Field:=2, Criteria1:=Criteria.Value
rng.Copy
Range("$BC$2:$BE$204").SpecialCells(xlCellTypeVisible).PasteSpecial
Большое спасибо
Ответ 1
AutoFilterMode будет True, если он включен, независимо от того, действительно ли фильтр применяется к определенному столбцу или нет. Когда это произойдет, ActiveSheet.ShowAllData
все равно будет выполняться, вызывая ошибку (поскольку фактическая фильтрация отсутствует).
У меня была такая же проблема, и я работал с
If (ActiveSheet.AutoFilterMode And ActiveSheet.FilterMode) Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
Это, по-видимому, предотвращает запуск ShowAllData, когда нет действительного фильтра, но с включенным AutoFilterMode.
Второй улов Or ActiveSheet.FilterMode
должен ловить расширенные фильтры
Ответ 2
Простым способом избежать этого является использование метода рабочей таблицы ShowAllDatap >
Автофильтр имеет тот же метод ShowAllData, который не выдает ошибку, если фильтр включен, но фильтр не установлен.
If ActiveSheet.AutoFilterMode Then ActiveSheet.AutoFilter.ShowAllData
Ответ 3
Ошибка ShowAllData method of Worksheet class failed
обычно возникает, когда вы пытаетесь удалить прикладной фильтр, если он не применяется.
Я не уверен, что вы пытаетесь удалить все AutoFilter
или просто удалить любой прикладной фильтр, но для каждого из них существуют разные подходы.
Чтобы удалить прикладной фильтр, но оставьте AutoFilter
на:
If ActiveSheet.AutoFilterMode Or ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
Обоснование вышеуказанного кода состоит в том, чтобы проверить, что существует AutoFilter
или применяется фильтр (это также приведет к удалению расширенных фильтров).
Чтобы полностью удалить AutoFilter
:
ActiveSheet.AutoFilterMode = False
В приведенном выше случае вы просто полностью отключите AutoFilter
.
Ответ 4
Я только что испытал ту же проблему. После некоторой пробной ошибки я обнаружил, что если выбор был справа от моей области фильтра. И количество показанных записей было равно нулю, ShowAllData потерпит неудачу.
Возможно, немного больше контекста. У меня есть несколько листов, каждый с фильтром. Я хотел бы установить некоторые стандартные фильтры на всех листах, поэтому я использую некоторые VBA, подобные этому
Sheets("Server").Select
col = Range("1:1").Find("In Selected SLA").Column
ActiveSheet.ListObjects("Srv").Range.AutoFilter Field:=col, Criteria1:="TRUE"
Этот код будет настраивать фильтр в столбце с заголовком «В выбранном SLA» и оставить все остальные фильтры без изменений. У этого есть неудачный побочный эффект, который я могу создать фильтр, который показывает нулевые записи. Это невозможно, используя только пользовательский интерфейс.
Чтобы избежать этой ситуации, я хотел бы, чтобы reset все фильтры, прежде чем применять фильтрацию выше. Мой код reset выглядел так:
Sheets("Server").Select
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
Обратите внимание, что я не перемещал выбранную ячейку. Если выбор был справа, он не удалял фильтры, таким образом, чтобы код фильтра создавал фильтр с нулевой строкой. Во второй раз, когда код запускается (в фильтре с нулевой строкой) ShowAllData завершится с ошибкой.
Обходной путь прост: переместите выделение внутри столбцов фильтра перед вызовом ShowAllDatap >
Application.Goto (Sheets("Server").Range("A1"))
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
Это было в Excel версии 14.0.7128.5000 (32-разрядная версия) = Office 2010
Ответ 5
Это будет работать Определите это, а затем позвоните, когда вам это нужно. (Хорошо для логики кнопок, если вы делаете кнопку очистки):
Sub ResetFilters()
On Error Resume Next
ActiveSheet.ShowAllData
End Sub
Ответ 6
У меня тоже такая же проблема. Я думаю, что причина в том,
1) Когда моя активная ячейка находится внутри таблицы, «ActiveSheet.ShowAllData» может работать.
2) Когда моя активная ячейка не в таблице,
«ActiveSheet.ShowAllData» не может работать. Используя этот код, ActiveSheet.ListObjects(«Srv»). Range.AutoFilter Field: = 1 может очистить фильтр.