Bỏ qua nội dung chính

Làm cách nào để lọc bảng Pivot dựa trên một giá trị ô cụ thể trong Excel?

Thông thường, chúng tôi đang lọc dữ liệu trong Pivot Table bằng cách chọn các mục trong danh sách thả xuống như được hiển thị trong ảnh chụp màn hình bên dưới. Trên thực tế, bạn có thể lọc bảng tổng hợp dựa trên giá trị trong một ô cụ thể. Phương pháp VBA trong bài viết này sẽ giúp bạn giải quyết vấn đề.

Lọc Bảng tổng hợp dựa trên giá trị ô cụ thể với mã VBA


Lọc Bảng tổng hợp dựa trên giá trị ô cụ thể với mã VBA

Mã VBA sau có thể giúp bạn lọc Bảng Pivot dựa trên giá trị ô cụ thể trong Excel. Hãy làm như sau.

1. Vui lòng nhập một giá trị mà bạn sẽ lọc Bảng Pivot dựa vào trước vào một ô (ở đây tôi chọn ô H6).

2. Mở trang tính có chứa Pivot Table, bạn sẽ lọc theo giá trị ô. Sau đó nhấp chuột phải vào tab trang tính và chọn Mã Chế độ xem từ trình đơn ngữ cảnh. Xem ảnh chụp màn hình:

3. Trong phần mở đầu Microsoft Visual Basic cho các ứng dụng cửa sổ, sao chép mã VBA bên dưới vào cửa sổ Mã.

Mã VBA: Lọc Bảng Pivot dựa trên giá trị ô

Private Sub Worksheet_Change(ByVal Target As Range)
'Update by Extendoffice 20180702
    Dim xPTable As PivotTable
    Dim xPFile As PivotField
    Dim xStr As String
    On Error Resume Next
    If Intersect(Target, Range("H6:H7")) Is Nothing Then Exit Sub
    Application.ScreenUpdating = False
    Set xPTable = Worksheets("Sheet1").PivotTables("PivotTable2")
    Set xPFile = xPTable.PivotFields("Category")
    xStr = Target.Text
    xPFile.ClearAllFilters
    xPFile.CurrentPage = xStr
    Application.ScreenUpdating = True
End Sub

Chú ý: Trong mã,

1) "Sheet1”Là tên của trang tính.
2) "PivotTable2”Là tên của Pivot Table.
3) Trường lọc trong bảng tổng hợp được gọi là "Phân loại".
4) Giá trị bạn muốn lọc bảng tổng hợp được đặt trong ô H6.
Bạn có thể thay đổi các giá trị biến ở trên khi cần.

4. Nhấn nút Khác + Q chìa khóa để đóng Microsoft Visual Basic cho các ứng dụng cửa sổ.

Sau đó, Pivot Table đang lọc dựa trên giá trị trong ô H6 như ảnh chụp màn hình bên dưới:

Bạn có thể thay đổi giá trị ô thành những giá trị khác nếu bạn cần.

Chú thích: Các giá trị bạn nhập vào ô H6 phải khớp chính xác với các giá trị trong danh sách Danh mục thả xuống của Pivot Table.


Các bài liên quan:

Công cụ năng suất văn phòng tốt nhất

🤖 Trợ lý AI của Kutools: Cách mạng hóa việc phân tích dữ liệu dựa trên: Thực thi thông minh   |  Tạo mã  |  Tạo công thức tùy chỉnh  |  Phân tích dữ liệu và tạo biểu đồ  |  Gọi các hàm Kutools...
Các tính năng phổ biến: Tìm, đánh dấu hoặc xác định các bản sao   |  Xóa hàng trống   |  Kết hợp các cột hoặc ô mà không làm mất dữ liệu   |   Vòng không có công thức hữu ích. Cảm ơn !
Siêu tra cứu: Nhiều tiêu chí VLookup    VLookup Nhiều Giá Trị  |   VLookup trên nhiều trang tính   |   Tra cứu mờ ....
Danh sách thả xuống nâng cao: Tạo nhanh danh sách thả xuống   |  Danh sách thả xuống phụ thuộc   |  Danh sách thả xuống nhiều lựa chọn ....
Trình quản lý cột: Thêm một số cột cụ thể  |  Di chuyển cột  |  Chuyển đổi trạng thái hiển thị của các cột ẩn  |  So sánh dãy và cột hữu ích. Cảm ơn !
Các tính năng nổi bật: Tiêu điểm lưới   |  Chế độ xem thiết kế   |   Thanh công thức lớn    Trình quản lý sổ làm việc & trang tính   |  Thư viện tài nguyên (Văn bản tự động)   |  Bảng chọn ngày   |  Kết hợp các bảng tính   |  Mã hóa/Giải mã ô    Gửi email theo danh sách   |  Siêu lọc   |   Bộ lọc đặc biệt (lọc in đậm/nghiêng/gạch ngang...) ...
15 bộ công cụ hàng đầu12 bản văn CÔNG CỤ (thêm văn bản, Xóa ký tự,...)   |   50 + Biểu đồ Các loại (Biểu đồ Gantt,...)   |   40+ Thực tế Công thức (Tính tuổi dựa trên ngày sinh,...)   |   19 chèn CÔNG CỤ (Chèn mã QR, Chèn ảnh từ đường dẫn,...)   |   12 Chuyển đổi CÔNG CỤ (Số thành từ, Chuyển đổi tiền tệ,...)   |   7 Hợp nhất & Tách CÔNG CỤ (Các hàng kết hợp nâng cao, Chia ô,...)   |   ... và nhiều hơn nữa

Nâng cao kỹ năng Excel của bạn với Kutools for Excel và trải nghiệm hiệu quả hơn bao giờ hết. Kutools for Excel cung cấp hơn 300 tính năng nâng cao để tăng năng suất và tiết kiệm thời gian.  Bấm vào đây để có được tính năng bạn cần nhất...

Mô tả


Tab Office mang lại giao diện Tab cho Office và giúp công việc của bạn trở nên dễ dàng hơn nhiều

  • Cho phép chỉnh sửa và đọc theo thẻ trong Word, Excel, PowerPoint, Publisher, Access, Visio và Project.
  • Mở và tạo nhiều tài liệu trong các tab mới của cùng một cửa sổ, thay vì trong các cửa sổ mới.
  • Tăng 50% năng suất của bạn và giảm hàng trăm cú nhấp chuột cho bạn mỗi ngày!
Comments (23)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Bonjour,

Merci beaucoup pour cette explication qui marche parfaitement.
En revanche, j'aimerais pouvoir utiliser ce code pour pouvoir filtrer deux tableaux croisés dynamiques en même temps qui sont sur la même feuille. La seule petite différence entre les deux, c'est qu'ils n'utilisent pas les mêmes sources. En revanche, le filtre sur lequel se base ces TDC est le même.

Pourriez-vous m'aider à faire évoluer ce code afin que cela fonctionne ?

Voici le code utilisé quand il marche avec un TCD :

Private Sub Worksheet_Change(ByVal Target As Range)
'Update by Extendoffice 20180702
Dim xPTable As PivotTable
Dim xPFile As PivotField
Dim xStr As String
On Error Resume Next
If Intersect(Target, Range("G4")) Is Nothing Then Exit Sub
Application.ScreenUpdating = False
Set xPTable = Worksheets("Cadrage").PivotTables("Tableau croisé dynamique7")
Set xPFile = xPTable.PivotFields("N°PROJET")
xStr = Target.Text
xPFile.ClearAllFilters
xPFile.CurrentPage = xStr
Application.ScreenUpdating = True
End Sub

Merci beaucoup
This comment was minimized by the moderator on the site
Hi Ambroise,

Sorry it's hard to amend this code to meet your needs. If you want to filter multiple pivot tables with a single filter, the methods in this article below may do you a favor:
How to connect a single slicer to multiple pivot tables in Excel?
This comment was minimized by the moderator on the site
Bonjour,
Merci beaucoup pour ces explications.

J'aimerai utiliser un filtre (1 cellule) en F4 par exemple qui filtrerait deux TCD qui sont sur la même feuille.

Cela fonctionne très bien avec un TCD mais dès que j'essaye de combiner le second, ça ne marche pas.
Pourriez-vous m'aider ?

Merci beaucoup
Ambroise
This comment was minimized by the moderator on the site
How does it work with Power Pivot, when using multiple tables? I recorded macro changing the value in filter. Made few changes to make the above code work. But it throws Type mismatch error. No matter what I do.
This comment was minimized by the moderator on the site
Hi DK,
The method does not work for Power Pivot. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
Thank you so much for this code! I got it working after adjusting to meet my fields, but after formatting some changes on my sheet now it doesn't work! I moved it from A1 to B1, changed some cell formatting to make it stand out, etc. Nothing too crazy but now it doesn't update when I change text in B1. Anyone have any ideas?

Private Sub Worksheet_Change(ByVal Target As Range)
'test
Dim xPTable As PivotTable
Dim xPFile As PivotField
Dim xStr As String

Dim x2PTable As PivotTable
Dim x2PFile As PivotField
Dim x2Str As String

Dim x3PTable As PivotTable
Dim x3PFile As PivotField
Dim x3Str As String

On Error Resume Next
If Intersect(Target, Range("b1")) Is Nothing Then Exit Sub

Application.ScreenUpdating = False

'tbl-1
Set xPTable = Worksheets("Line Report").PivotTables("PivotTable7")
Set xPFile = xPTable.PivotFields("Utopia Source")
xStr = Target.Text
xPFile.ClearAllFilters
xPFile.CurrentPage = xStr

'tbl-2
Set x2PTable = Worksheets("Line Report").PivotTables("PivotTable2")
Set x2PFile = x2PTable.PivotFields("Utopia Source")
x2Str = Target.Text
x2PFile.ClearAllFilters
x2PFile.CurrentPage = x2Str

'tbl-3
Set x3PTable = Worksheets("Line Report").PivotTables("PivotTable3")
Set x3PFile = x3PTable.PivotFields("Utopia Source")
x3Str = Target.Text
x3PFile.ClearAllFilters
x3PFile.CurrentPage = x3Str

Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
Hi Lance,
I tested your code and it works fine in my case. Changing the cell format does not affect the operation of the code.
This comment was minimized by the moderator on the site
Hello!

I am new with VBA and I would like to have a code to select a pivot filter based on a cell range.
How can I change "CurrentPage" to be a range value ?
Thank you!!
-------------------------------------------------------------------------------------------
Sub PrintTour()

ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Bereich 1].[Tour].[Tour ]"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Bereich 1].[Tour].[Tour]"). _
CurrentPage = "[Bereich 1].[Tour lt. Anlieferungstag].&[4001-01]"
End Sub
This comment was minimized by the moderator on the site
What if i want to link the selection cell to a different tab? This is my code so far
Private Sub Worksheet_Change(ByVal Target As Range)
Dim xPTable1 As PivotTable
Dim xPFile1 As PivotField
Dim xStr1 As String
On Error Resume Next
If Intersect(Target, Range("B1")) Is Nothing Then Exit Sub
Application.ScreenUpdating = False
Set xPTable1 = Worksheets("SM_SKU PIVOTS").PivotTables("PivotTable1")
Set xPFile1 = xPTable1.PivotFields("Geography")
xStr1 = Target.Text
xPFile1.ClearAllFilters
xPFile1.CurrentPage = xStr1
Application.ScreenUpdating = True

Dim xPTable2 As PivotTable
Dim xPFile2 As PivotField
Dim xStr2 As String
On Error Resume Next
If Intersect(Target, Range("B1")) Is Nothing Then Exit Sub
Application.ScreenUpdating = False
Set xPTable2 = Worksheets("SM_SKU PIVOTS").PivotTables("PivotTable4")
Set xPFile2 = xPTable2.PivotFields("Geography")
xStr2 = Target.Text
xPFile2.ClearAllFilters
xPFile2.CurrentPage = xStr2
Application.ScreenUpdating = True

Dim xPTable3 As PivotTable
Dim xPFile3 As PivotField
Dim xStr3 As String
On Error Resume Next
If Intersect(Target, Range("B1")) Is Nothing Then Exit Sub
Application.ScreenUpdating = False
Set xPTable3 = Worksheets("SM_SKU PIVOTS").PivotTables("PivotTable8")
Set xPFile3 = xPTable3.PivotFields("Geography")
xStr3 = Target.Text
xPFile3.ClearAllFilters
xPFile3.CurrentPage = xStr3
Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
Olá, gostaria de saber se quisesse filtrar mais de uma categoria como poderia ser?
This comment was minimized by the moderator on the site
I would like to use multiple Worksheet Change code in same worksheet. How to do that? My code is as below:
Private Sub Worksheet_Change(ByVal Target As Range)
'Pivot table filter based on cell value
Dim xPTable As PivotTable
Dim xPFile As PivotField
Dim xStr As String
On Error Resume Next
If Intersect(Target, Range("D20:D21")) Is Nothing Then Exit Sub
Application.ScreenUpdating = False
Set xPTable = Worksheets("Sheet1").PivotTables("PivotTable2")
Set xPFile = xPTable.PivotFields("Designation")
xStr = Target.Text
xPFile.ClearAllFilters
xPFile.CurrentPage = xStr
Application.ScreenUpdating = True
End Sub

Private Sub Worksheet_Change2(ByVal Target As Range)
'Pivot table filter based on cell value 2
Dim xPTable As PivotTable
Dim xPFile As PivotField
Dim xStr As String
On Error Resume Next
If Intersect(Target, Range("H20:H21")) Is Nothing Then Exit Sub
Application.ScreenUpdating = False
Set xPTable = Worksheets("Sheet1").PivotTables("PivotTable2")
Set xPFile = xPTable.PivotFields("Offering")
xStr = Target.Text
xPFile.ClearAllFilters
xPFile.CurrentPage = xStr
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Is this possible with google sheets? If so, how?
This comment was minimized by the moderator on the site
Google Sheets will not require any pivot table. you can directly perform through Filter Function
This comment was minimized by the moderator on the site
I was able to modify/filter 3 different pivots which are on the same tab. I also added a row in my data set "No Data Found", otherwise it left the filter to "ALL" which I didn't want. The above was a great help to earn me Kudos with management so I wanted to share. Note the (All) is case sensitive took me a bit to figure that out.
Private Sub Worksheet_Change(ByVal Target As Range)
'test
Dim xPTable As PivotTable
Dim xPFile As PivotField
Dim xStr As String

Dim x2PTable As PivotTable
Dim x2PFile As PivotField
Dim x2Str As String

Dim x3PTable As PivotTable
Dim x3PFile As PivotField
Dim x3Str As String

On Error Resume Next
If Intersect(Target, Range("a2:e2")) Is Nothing Then Exit Sub

Application.ScreenUpdating = False

'tbl-1
Set xPTable = Worksheets("Graphical").PivotTables("PivotTable1")
Set xPFile = xPTable.PivotFields("MR Department - Department")
xStr = Target.Text
xPFile.ClearAllFilters
xPFile.CurrentPage = xStr
If xPFile.CurrentPage = "(All)" Then xPFile.CurrentPage = "No Data Found"

'tbl-2
Set x2PTable = Worksheets("Graphical").PivotTables("PivotTable2")
Set x2PFile = x2PTable.PivotFields("MR Department - Department")
x2Str = Target.Text
x2PFile.ClearAllFilters
x2PFile.CurrentPage = x2Str
If x2PFile.CurrentPage = "(All)" Then x2PFile.CurrentPage = "No Data Found"

'tbl-3
Set x3PTable = Worksheets("Graphical").PivotTables("PivotTable3")
Set x3PFile = x3PTable.PivotFields("MR Department - Department")
x3Str = Target.Text
x3PFile.ClearAllFilters
x3PFile.CurrentPage = x3Str
If x3PFile.CurrentPage = "(All)" Then x3PFile.CurrentPage = "No Data Found"

Application.ScreenUpdating = True

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