Перейти к основному содержанию

Как сохранить слайсер сводной таблицы с прокруткой листа в Excel?

При работе со сводной таблицей вы можете вставлять срезы для визуальной фильтрации данных в таблице. В этой статье говорится о том, чтобы срез сводной таблицы всегда был видимым при прокрутке рабочего листа.

Продолжайте движение слайсера сводной таблицы с прокруткой листа с помощью кода VBA


Продолжайте движение слайсера сводной таблицы с прокруткой листа с помощью кода VBA

Следующий сценарий VBA может помочь вам сохранить срез сводной таблицы вместе с листом. Пожалуйста, сделайте следующее.

1. нажмите другой + F11 клавиши одновременно, чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окно, дважды щелкните Эта рабочая тетрадь на левой панели проекта, а затем скопируйте и вставьте приведенный ниже код VBA в ThisWorkbook (Код) окно. Смотрите скриншот:

Код VBA: продолжайте движение слайсера сводной таблицы с прокруткой рабочего листа

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    Dim ShF As Shape
    Dim ShM As Shape
    'specify a slicer
    Application.ScreenUpdating = False
    Set ShF = ActiveSheet.Shapes("Column1")
    Set ShM = ActiveSheet.Shapes("Column2")
    'change position of the slicer
    With Windows(1).VisibleRange.Cells(1, 1)
        ShF.Top = .Top
        ShF.Left = .Left + 300
        ShM.Top = .Top
        ShM.Left = .Left + 100
    End With
    Application.ScreenUpdating = True
End Sub

Заметки:

1). В коде Column1 и Column2 - это названия срезов.

2). Вы можете указать положение срезов при прокрутке листа в коде.

3). И вы можете добавить в код дополнительные слайсеры или удалить из него по мере необходимости.

3. нажмите другой + Q ключи, чтобы закрыть Microsoft Visual Basic для приложений диалоговое окно окна.

С этого момента указанные срезы будут перемещаться вместе с активной ячейкой при прокрутке листа. Смотрите скриншот:


Статьи по теме:

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (10)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Okay, so the title says "How To Keep Slicer Of Pivot Table Moving With Worksheet Scrolling In Excel?", but this VBA code only does it for the current selected cell, how can we do it for the scrolling of the workbook, and not just the selected cell?
This comment was minimized by the moderator on the site
I have 4 slicers which have been grouped together by selecting all 4 and the right clicking to use the group command.

Is it possible to assign this VBA by a group? How do you label the group and write the VBA to recognize it as one?
This comment was minimized by the moderator on the site
Hi Michael,
Sorry can't help with this. Thanks for your comment.
This comment was minimized by the moderator on the site
What does the first row indicate and how do we customize it to suit our slicer?
I'm very confused about that on basically every line.
This comment was minimized by the moderator on the site
Dear Katie
I don't know if I totally understand your question.
As I mentioned in above Notes, you need to replace Column1 and Column2 with the names of your slicers in the code in order to keep your slicer scrolling with the worksheet.
This comment was minimized by the moderator on the site
Hi,
Thank you for this VBA.

I have absolutely no idea about VBA and hence my question.

I used this VBA and I had a question.
How can i alter this VBA so that it works only for one sheet.

Right now, I have 8 sheets and every time i go to another sheet, it fails and asks me to end or debug.
I have done exactly the way as shown above.


This is my VBA here..
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Dim ShF As Shape
Dim ShM As Shape
'specify a slicer
Application.ScreenUpdating = False
Set ShF = ActiveSheet.Shapes("Client 1")
Set ShM = ActiveSheet.Shapes("Reminder 1")
'change position of the slicer
With Windows(1).VisibleRange.Cells(1, 1)
ShF.Top = .Top + 2
ShF.Left = .Left + 475
ShM.Top = .Top + 180
ShM.Left = .Left + 475
End With
Application.ScreenUpdating = True
End Sub


Please help.
This comment was minimized by the moderator on the site
Dear John,
Shift to the worksheet you want the VBA code only work for, then right click the Sheet tab and select View Code from the context menu.
And then copy and paste below VBA code into the opening Code window. See below screenshot:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ShF As Shape
Dim ShM As Shape
'specify a slicer
Application.ScreenUpdating = False
Set ShF = ActiveSheet.Shapes("Fruit")
Set ShM = ActiveSheet.Shapes("Sale")
'change position of the slicer
With Windows(1).VisibleRange.Cells(1, 1)
ShF.Top = .Top
ShF.Left = .Left + 300
ShM.Top = .Top
ShM.Left = .Left + 100
End With
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi,I have updated my code as you have indicated. The slicer no longer scrolls along with the window however if I click in a new cell then the slicer will move. Is this the correct behavior?
This comment was minimized by the moderator on the site
Dear Crystal,

Thank you so very much for the code.
I did exactly as you said and it works like a charm.

Really appreciate it.
Cheers :)
This comment was minimized by the moderator on the site
Hi,
Thank you for this VBA.

I have absolutely no idea about VBA and hence my question.

I used this VBA and I had a question.
How can i alter this VBA so that it works only for one sheet.

Right now, I have 8 sheets and every time i go to another sheet, it fails and asks me to end or debug.
I have done exactly the way as shown above.


This is my VBA here..
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Dim ShF As Shape
Dim ShM As Shape
'specify a slicer
Application.ScreenUpdating = False
Set ShF = ActiveSheet.Shapes("Client 1")
Set ShM = ActiveSheet.Shapes("Reminder 1")
'change position of the slicer
With Windows(1).VisibleRange.Cells(1, 1)
ShF.Top = .Top + 2
ShF.Left = .Left + 475
ShM.Top = .Top + 180
ShM.Left = .Left + 475
End With
Application.ScreenUpdating = True
End Sub


Please help.
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations