我想问一下我应该使用什么逻辑来搜索范围D中的范围A值。如果范围A值不等于范围D中的任何一个,则想在范围D下添加它。 / p>
我出来了这段代码。但是对于Range1,是否可以设置范围A中包含值的最后一行?
scene.getStylesheets().add("style.css");
答案 0 :(得分:0)
逻辑是:
在A
中设置指向第一个单元格的指针开始循环
在D中找到指针的值(使用WorksheetFunction.MATCH或FIND)
如果没有找到,那么
在D
中查找下一个空白行将指针值复制到该行D列
(可选,A中的空白单元格)
推进指向下一个单元格的指针
如果您已到达A中的最后一个单元格然后停止,则返回循环开始
现在您可以将其转换为VBA代码
答案 1 :(得分:0)
永远不要为VBA已使用的过程使用名称。您将过程命名为Sub find()
,但find
已经是VBA方法的名称。这将很快或后来导致奇怪的问题,并且是一种非常糟糕的做法。
而是使用有意义的名称,例如Sub FindMissingProductsAndCopyThem()
。
我建议使用以下代码:
Option Explicit
Public Sub FindMissingProductsAndCopyThem()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1") 'define which worksheet
Dim lRowSource As Long
lRowSource = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'find last row in column A
Dim lRowDestination As Long
lRowDestination = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row 'find last row in column D
Dim FoundRow As Long
Dim iRow As Long
For iRow = 2 To lRowSource 'loop throug data of column A
FoundRow = 0 'initialize/reset
On Error Resume Next 'next line throws an error if not matched, catch that error
'try to find/match the data of column A in column D
FoundRow = Application.WorksheetFunction.Match(ws.Cells(iRow, "A"), ws.Columns("D"), 0)
On Error GoTo 0 're-activate error reporting
'if Match threw an error, then FoundRow is still 0
If FoundRow = 0 Then 'product was not found, so add it
lRowDestination = lRowDestination + 1
ws.Cells(lRowDestination, "D").Value = ws.Cells(iRow, "A")
End If
Next iRow
End Sub