繁体   English   中英

来自A列的VBA检查值在另一个工作簿中

[英]VBA check value from column A exists in another workbook

我正在尝试构建一个宏,该宏循环遍历colA中的一系列值,并检查它们是否存在于另一个工作簿中。 我想在其中一个中将其标记为“已工作” /“未工作”

图片 关于从哪里开始的任何指导?

这是您要查找的示例。 请记住,必须在同一Excel实例中打开两个工作簿。

Sub check()

Dim i As Integer, k As Integer, j As Integer 'Define your counting variables
Dim Report1 As Worksheet, bReport As Workbook, Report2 As Worksheet, bReport2 As Workbook 'Define your workbook/worksheet variables

Set Report1 = Excel.ActiveSheet 'Assign active worksheet to report1
Set bReport = Report1.Parent 'Assign the workbook of report 1 to breport


On Error GoTo wbNotOpen 'If an error occurs while accessing the named workbook, send to the "wbNotOpen" line.
Set bReport2 = Excel.Workbooks("otherworkbookname.xlsm") 'Assign the other workbook which you are cross-referencing to the bReport2 variable.
Set Report2 = bReport2.Worksheets("otherworksheetname") 'Do the same with the worksheet.
On Error GoTo 0 'Reset the error handler (to undo the wbNotOpen line.)

k = Report1.UsedRange.Rows.Count 'Get the last used row of the first worksheet.
j = Report2.UsedRange.Rows.Count 'Get the last used row of the second worksheet.

For i = 2 To k 'Loop through the used rows of the first worksheet. I started at "2" to omit the header.
    'Next, I used the worksheet function "countIf" to quickly check if the value exists in the given range. This way we don't have to loop through the second worksheet each time.
    If Application.WorksheetFunction.CountIf(Report2.Range(Report2.Cells(2, 1), Report2.Cells(j, 1)), Report1.Cells(i, 1).Value) > 0 Then
        Report1.Cells(i, 5).Value = "Worked" 'If the value was found, enter "Worked" into column 5.
    Else
        Report1.Cells(i, 5).Value = "Not worked" 'If the value wasn't found, enter "Not worked" into column 5.
    End If
Next i




Exit Sub
'This is triggered in the event of an error while access the "other workbook".
wbNotOpen:
MsgBox ("Workbook not open. Please open all workbooks then try again.")
Exit Sub

End Sub

此链接还包括告诉您如何检查另一个工作簿中是否存在单元的步骤。 这些评论很有用。

感谢#Lopside的解决方案,我对他的代码进行了整理以提出该解决方案。 这似乎可行。

{       
Sub CheckValue()

Dim S1 As Worksheet
Dim S2 As Worksheet

Dim i As Integer
Dim k As Integer
Dim j As Integer

Set S1 = Worksheets("Sheet1")
Set S2 = Worksheets("Sheet2")

k = S1.UsedRange.Rows.Count
j = S2.UsedRange.Rows.Count

For i = 1 To k
If Application.WorksheetFunction.CountIf(S2.Range(S2.Cells(2, 1), S2.Cells(j, 1)), S1.Cells(i, 1).Value) > 0 Then
    S1.Cells(i, 5).Value = "Worked" 'If the value was found, enter "Worked" into column 5.
Else
    S1.Cells(i, 5).Value = "Not worked" 'If the value wasn't found, enter "Not worked" into column 5.
End If
Next i
End Sub

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM