简体   繁体   English

如何使用偏移量使用VBA扩展命名范围

[英]How to extend named range with VBA using offset

I have the following code that I am using in VBA for excel. 我有以下代码,我在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") 它遍历我的表,并根据B列(“OSI”)和C列(i,e“报告”)中的值创建命名范围

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. 当我希望范围从列D到列F时,它正在创建一个两列宽的命名范围(列D到列E)。

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. 使用Range.Resize属性调整范围的大小。 Offset only moves a range. Offset仅移动范围。

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 并且您希望将它扩展1列到F列,您可以使用它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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