[英]Find a range of multiple cells in another sheet
我正在嘗試增強當前的腳本。 Sheet1和Sheet2在A列中僅包含文件路徑名稱。如果在Sheet1中找不到Sheet2中的文件路徑,則會將其復制到工作表3中。
'row counter
x = 1
'Initiate Variables
Set wb = ActiveWorkbook
Set ws1 = wb.Sheets("Sheet1")
Set ws2 = wb.Sheets("Sheet2")
'create a new sheet 3, delete old one if it exists
If Sheets.Count > 2 Then
Application.DisplayAlerts = False
Sheets(3).Delete
Application.DisplayAlerts = False
End If
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = "Sheet3"
Set ws3 = wb.Sheets("Sheet3")
'Get row count to know how many times to loop
rowCount2 = ws2.Range("A1").End(xlDown).Row
'compare filepaths from sheet2 to sheet1
'if there is a difference, that difference is put on sheet 3
For i = 1 To rowCount2
FilePath = ws2.Cells(i, 1)
With Sheets("Sheet1").Range("A:A")
Set CellId = .Find(What:=FilePath, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not CellId Is Nothing Then
'do nothing if filepath is found in both sheets
Else
'put the filepath from file2 not found in file1, into
'sheet 3
ws3.Cells(x, 1) = FilePath
x = x + 1
End If
End With
Next I
我想做的是,能夠引用一系列要比較的單元格,而不僅僅是從A列中進行比較。不僅僅是A列中的文件路徑,而是最后保存於B列,最后保存於C列,因此,我不僅要檢查文件路徑中的差異,還希望多列中的差異。 因此,可能存在相同的文件路徑,但是另一天卻有人打開了它。 我需要抓住這種差異。 我不知道如何引用多個單元格的范圍。 所以我需要修正這段代碼:
FilePath = ws2.Cells(i, 1)
With Sheets("Sheet1").Range("A:A")
如果有更簡單的方法可以解決這個問題,我可以征詢您的意見。
在'do nothing if filepath is found in both sheets
部分中,放置類似以下內容的內容:
k = ws2.Cells(1,ws2.Columns.Count).End(xlToleft).Column
For j = 2 to k
If ws2.Cells(i, j).Value <> CellId.Offset(, j - 1).Value Then
CellId.EntireRow.Copy ws.Cells(x,1).EntireRow
x = x +1
Exit For
'or whatever code you need to move to sheet3
End If
Next
比較多個列表時使用字典。 這樣,我只遍歷每個列表一次。
Sub CopyMissingFileNames()
Dim filepath As Range, Target As Range
Dim dictFilePaths As Object
Set dictFilePaths = CreateObject("Scripting.Dictionary")
With Worksheets("Sheet1")
For Each filepath In .Range("A2", .Range("A" & Rows.Count).End(xlUp))
If Not dictFilePaths.Exists(filepath.Text) Then dictFilePaths.Add filepath.Text, ""
Next
End With
With Worksheets("Sheet2")
For Each filepath In .Range("A2", .Range("A" & Rows.Count).End(xlUp))
If Not dictFilePaths.Exists(filepath.Text) Then
Set Target = Worksheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1)
filepath.EntireRow.Copy Target
End If
Next
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.