简体   繁体   中英

Searching a Range in Excel VBA

I have a string array, and in each slot of the array is a 'range of columns' in a string format eg "B:J" "k:W" "AC:AG"

The method is being passed a string which is a column name eg "C"

I need to search see if "C" is inside "B:J".

So basically it needs to check to see if "C" is in "BCDEFGHIJ" which it is and if it is break from a loop

But if I input "A" it should then go to the next slot in the array.

Thank

This function will return the position in the array where the single column is included in the range. It uses the Intersect property to determine if the two ranges intersect.

Function ArrayPos(sColLetter As String, vaRanges As Variant) As Long

    Dim i As Long
    Dim sh As Worksheet
    Dim lReturn As Long

    Set sh = Sheet1

    For i = LBound(vaRanges) To UBound(vaRanges)
        If Not Intersect(sh.Columns(sColLetter), sh.Columns(vaRanges(i))) Is Nothing Then
            lReturn = i
            Exit For
        End If
    Next i

    ArrayPos = lReturn

End Function

It's used like this, from the Immediate Window for example

?arraypos("M",array("B:J","K:W"))
 1 

You would want to add some error checking to make sure the arguments can be converted to ranges, but I'll leave that to you. You could do this without Range objects by splitting the range string on colon and comparing the ASCII values of the letters.

You might take a look at

How to convert a column number (eg. 127) into an excel column (eg. AA)

sheet.Application.ActiveCell.Column //for current selected column
int col=sheet.Range("A").Column; // for any choosen column

returns current column number, just apply the same for your range B:J, check if J (10) > C (3) > B ( 2)

Then you can say that it is inside that range.

In case of need the other way around this function with the link I gave you.

ConvertToAlphaColumnReferenceFromInteger(sheet.Application.ActiveCell.Column)

Done for C#/.NET

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