Home » excel » excel – How to do a.Find(after) in VBA?

excel – How to do a.Find(after) in VBA?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to find a cell with a given key. The data in the sheet is similar to…

SECTION1    KEY1
            KEY2
            KEY3
SECTION2    KEY4

Although the keys are currently unique, I suspect that may not be the case in the future. So I do two lookups, one on the section in column A:

Dim S As Range
Set S = ThisWorkbook.Sheets("Data").Range("A:A").Find("SECTION1", , xlValues, xlWhole)

And that returns, in this case (14,1). Perfect. But now I try to look for the key using after, which hopefully reduces the chance of a collision:

Dim K As Range
Set K = ThisWorkbook.Sheets("Data").Range("B:B").Find("KEY1", S.Cells(S.Row - 1, 2), xlValues, xlWhole)

And that returns a type mismatch. Remove the AFTER clause and it works fine. According to the docs, it seems this should be a range, but yikes that page is confusing.

I’ve tried multiple variations for the clause, including S, S.Cells and others, but they all give me a type mismatch. Anyone have a working version and an explanation of what’s going on?

How to&Answers:

You are probably thinking of Offset, when you are using the After parameter. As a rule of a thumb, the After:= should be a part of the range of the .Find


The second problem is that the range s is only with one column (and probably one row as well). You are somehow referring a second column here – S.Cells(S.Row - 1, 2), and it does not like it at all. Change the 2 to 1.


To understand what the range should look like, try to print the address of the After, before assigning it in the Find.

Debug.Print S.Cells(S.Row - 1, 2).Address should give some cell address within the second column (B) in order to make the whole code working. A hint – if you want the After parameter to be the same row as the found cell in column A try something like this – S.Cells(1,1).Offset(0,1) for After:=.

Answer:

Looking the docs, it says Notice that After must be a single cell in the range.

So the After Argument must be a single cell inside the range where you are searching (in your example, a cell inside B:B).

Using notation S.Cells(S.Row - 1, 2), yes, you mean the cell inside range B:B and same row that SECTION1, but S is referenced to a cell outside B:B, and probably that’s causing the error.

This works for me:

Set K = ThisWorkbook.Sheets("Data").Range("B:B").Find("KEY1", Range("B" & S.Cells(1, 1).Row), xlValues, xlWhole)

Is the same than yours but notation Range("B" & S.Cells(1, 1).Row) makes sure you are referencing to a cell inside B:B.

I know, it’s kind of annoying, but it works.