本文介绍了来自A列的VBA检查值存在于另一个工作簿中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个宏,该宏在colA中的一系列值之间循环,并检查它们是否存在于另一个工作簿中.我想在其中之一中将其标记为有效"/无效"
I am trying to build a macro that loops through a range of values within colA and check if they exist with another workbook. In one of them I would like to mark it "Worked"/"Not Worked"
关于从哪里开始的任何指导?
Any guidance on where to start?
推荐答案
示例
这是您要查找的示例.请记住,两个工作簿都必须在同一Excel实例中打开.
Example
Here is an example of what you're looking for. Remember that both the workbooks have to be opened in the same instance of 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
此链接还包括一些步骤,这些步骤告诉您如何检查另一个工作簿中是否存在一个单元格.这些评论很有用.
This link also includes steps that tell how to check if a cell exists in another workbook. The comments are useful.
这篇关于来自A列的VBA检查值存在于另一个工作簿中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!