简体   繁体   中英

VBA to search from one excel to another excel and display cell address

I have two excel file. I am searching the data in another file with the unique email ID. I am taking email ID from one excel file one by one and searching in another excel file. Once the data is found, I want the cell address. I am getting error on " MsgBox cell.Address " code as "Object variable or with block variable not set". Please assist

Dim myFileNameDir As String
Dim myFileNameDir2 As String
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim emailID As String
Dim cell As Range
Dim II As Integer
Dim III As Integer

myFileNameDir2 = TextBox2.Value
Workbooks.Open Filename:=myFileNameDir2, UpdateLinks:=0
Set ws2 = Worksheets(1)

myFileNameDir = TextBox1.Value
Workbooks.Open Filename:=myFileNameDir, ReadOnly:=True, UpdateLinks:=0
Set ws = Worksheets(1)


II = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row

For III = 2 To II
emailID = ws2.Cells(III, "D").Value

Set cell = ws.Range("AA2:AA1048576").find(emailID, LookAt:=xlWhole)
MsgBox cell.Address

Next III

Most likely in this case the error is coming because the Find method is not finding a match, so there's nothing to return. The Find method can be tricky to work with from VBA, especially when looking at xlWhole. Are you sure that there's a matching value in the other sheet? Are you sure the match is exact? Etc. Even merged cells can throw the Find method off.

Normally using worksheet functions will slow things down, but in this case you might be best off using a MATCH function to find the matching row, then returning that value into your cell address.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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