[英]Filter the data based on another workbook cell value using VBA
由於我仍在學習,我陷入了應用條件以根據源工作簿單元格值過濾目標工作表中的兩列。
例如。 來源:具有 Q2 的 A1 列和具有 d104 的列 b2 我需要將其用作目標工作簿中的過濾器並刪除現有的可見過濾值並將其替換為復制的數據。
我有邏輯只替換沒有過濾器的數據。 但是如何使用過濾器來實現?
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim CopyLastRow As Integer
Dim DestlastRow As Integer
'1. open the workbook to copy from
Workbooks.Open "C:\Forecast.xlsx" -- target
'2. Define each workbook
Set wsCopy = ThisWorkbook.Sheets("Input Data") --source
Set wsDest = Workbooks("Imports PY Plan Forecast.xlsx").Sheets("Source")
'3. Define last row in source data
CopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Worksheets("Input Data").Range("A2:F" & CopyLastRow).Copy wsDest.Range("A2")
'4. close and save source file
Workbooks("Imports PY Plan Forecast.xlsx").Close SaveChanges:=True
End Sub```
為了實現過濾行,刪除和粘貼值,您可以在設置工作簿完成后編寫如下代碼:
'Filter column A and column B based on value
Worksheets("Input Data").Range("A1:AE" & CopyLastRow).AutoFilter Field:=1, Criteria1:="Q2"
Worksheets("Input Data").Range("A1:AE" & CopyLastRow).AutoFilter Field:=2, Criteria1:="d104"
'Assuming your data start from row 2, will only delete visible cell
Worksheets("Input Data").range("A2:A" & CopyLastRow).entirerow.delete
'And copy value in visible cell using special cell function
ThisWorkbook.Worksheets("Input Data").Range("A2:F" & CopyLastRow).SpecialCells(xlCellTypeVisible).Copy wsDest.Range("A2")
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim wsfilter As Worksheet
Dim CopyLastRow As Integer
Dim DestlastRow As Integer
Dim ws As Worksheet, rng As Range, LstRw As Long
'1. open the workbook to copy from
Workbooks.Open "C:Forecast.xlsx"
'2. Define each workbook
Set wsCopy = ThisWorkbook.Sheets("Input Data")
Set wsDest = Workbooks("Forecast.xlsx").Sheets("Source")
Set wsfilter = ThisWorkbook.Sheets("HR - Source")
'3. Define last row in source data
CopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
'4.Filter column A and column B based on value
wsDest.Range("A1:F" & CopyLastRow).AutoFilter Field:=3, Criteria1:=wsfilter.Range("E1").Value
wsDest.Range("A1:F" & CopyLastRow).AutoFilter Field:=5, Criteria1:=wsfilter.Range("D2").Value & "*"
'5.Delet Visible data
Application.DisplayAlerts = False
ActiveSheet.UsedRange.Offset(1, 0).Resize(ActiveSheet.UsedRange.Rows.Count - 1).Rows.Delete
Application.DisplayAlerts = True
'6. Copy data from Input Data to Forecast Source
ThisWorkbook.Worksheets("Input Data").Range("A2:F" & CopyLastRow).SpecialCells(xlCellTypeVisible).Copy wsDest.Range("A2")
On Error Resume Next
wsDest.ShowAllData
On Error GoTo 0
'7. close and save source file
Workbooks("Forecast.xlsx").Close SaveChanges:=True
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.