Try   HackMD

#分享 Excel篩選功能如何以儲存格作為篩選依據

LHB阿好伯, 2020/04/25

tags: Excel

紀錄一下這幾天在Telegran的討論群中解決的問題

在Excel中有一個非常好用的篩選功能

正常來說使用上是只需要勾選所需資料類型就可以進行篩選

這次遇到情況是希望能以特定儲存格鍵入資料作為篩選依據

範例如下:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

在說明解法前先說明內建功能中也可以已鍵入資料的方式進行篩選

最主要方式是可以進行文字篩選

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

則這次解決方式主要透過Excel VBA進行處理

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Private Sub Worksheet_Change(ByVal Target As Range) ActiveSheet.Columns("A:B").AutoFilter Field:=1, Criteria1:=Range("C1") '篩選依據 End Sub

這段程式碼主要利用Worksheet.change當使用者或外部連結變更工作表中的儲存格時會自動執行後續程式碼

再搭配上自動篩選Range.AutoFilter的程式碼進行修改所達成
Field則是篩選的基準之欄位
Criteria1則為篩選的依據

上述程式碼主要是在同一活頁簿下作業

在後來提出若是將原本工作表1中的篩選依據儲存格放置於工作表2中

若要達成則需要修改其中的ActiveSheet使用中活頁簿

改成Worksheets("工作表1")指定的活頁簿名稱

並將程式碼放置於工作表2的project中

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Private Sub Worksheet_Change(ByVal Target As Range) Worksheets("工作表1").Range("A:B").AutoFilter Field:=1, Criteria1:=Worksheets("工作表2").Range("A1") '篩選依據 End Sub

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

參考資料

Worksheet.change 方法 (Excel)
[Range.AutoFilter 方法 (Excel)](https://docs.microsoft.com/zh-tw/office/vba/api/excel.range.autofilter)
Application.ActiveSheet 屬性 (Excel)

全文分享至

https://www.facebook.com/LHB0222/

有疑問想討論的都歡迎於下方留言

喜歡的幫我分享給所有的朋友 \o/

有所錯誤歡迎指教

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →