简体   繁体   中英

How to extend named range with VBA using offset

I have the following code that I am using in VBA for excel.

It goes through the my table, and creates a named range based on the values in column B ("OSI") and column C (i,e "Reporting")

Sub Round2()

Set sht = ThisWorkbook.Worksheets("Features")

'Reporting and OSI

Set featuresRng = sht.Range(sht.Range("B1"), sht.Range("C" & sht.Rows.Count).End(xlUp))
rngArray = featuresRng
ReDim NewArr(1 To 1)
y = 1
For i = 1 To UBound(rngArray)
    If rngArray(i, 2) = "Reporting" And rngArray(i, 1) = "OSI" Then
        ReDim Preserve NewArr(1 To y)
        NewArr(y) = featuresRng.Rows(i).Offset(0, 2).Address
        y = y + 1

    End If
Next i

sRng = Join(NewArr, Application.DecimalSeparator)
ThisWorkbook.Names.Add "OSIRep", sht.Range(sRng)

End Sub () 

It is creating a named range that is two columns wide (column D to column E) when I want the range instead to go from column D to column F.

I am not sure which parts of the code to edit - I appreciate this is probably a very easy solution but I am having trouble!

Use the Range.Resize property to resize a range. Offset only moves a range.

For example if your range is defined as

Dim rng As Range
Set rng = Range("D:E")

and you want to extend it by 1 column to column F you can do it with

Set rng = rng.Resize(ColumnSize:=rng.Columns.Count + 1) 'extend range by 1 column
Debug.Print rng.Address 'will return $D:$F

改变这个

NewArr(y) = featuresRng.Rows(i).Resize(1, 5).Offset(0, 3).Address

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