我有以下代码
Sub NamedRange()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim rangeC1F As Range
Dim rangeC2F As Range
Dim rangeC3F As Range
Dim rangeC4F As Range
Dim rangeP1F As Range
Dim rangeP2F As Range
Dim rangeP3F As Range
Dim rangeP4F As Range
For Each ws In ThisWorkbook.Worksheets
ws.Activate
With ActiveWindow
Set rangeC1F = ws.Range("G3:G100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_C1F", " ", "_"), RefersTo:=rangeC1F
Set rangeC2F = ws.Range("T3:T100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_C2F", " ", "_"), RefersTo:=rangeC2F
Set rangeC3F = ws.Range("AG3:AG100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_C3F", " ", "_"), RefersTo:=rangeC3F
Set rangeC4F = ws.Range("AT3:AT100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_C4F", " ", "_"), RefersTo:=rangeC4F
Set rangeP1F = ws.Range("BG3:BG100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_P1F", " ", "_"), RefersTo:=rangeP1F
Set rangeP2F = ws.Range("BT3:BT100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_P2F", " ", "_"), RefersTo:=rangeP2F
Set rangeP3F = ws.Range("CG3:CG100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_P3F", " ", "_"), RefersTo:=rangeP3F
Set rangeP4F = ws.Range("CT3:CT100")
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_P4F", " ", "_"), RefersTo:=rangeP4F
End With
Next
Application.ScreenUpdating = True
End Sub
此代码使我能够为大量工作表创建定义/命名范围。但是,使用当前代码,范围是静态的。我想用" offset" -function使它们变得动态。 范围的长度由范围C1F的细胞F1的值,范围C2F的细胞S1,范围C3F的细胞AF1,范围C4F的细胞AS1,范围P1F的细胞BF1,范围P2F的细胞BS1,细胞CF1的值确定。范围P3F,单元CS1,范围P4F。起始细胞保持不变(细胞G3,T3,AG3,...,CT3)
如何在现有模块中正确插入偏移功能?
谢谢你!答案 0 :(得分:0)
第一个,范围C1F,可以更改为:
ws.Names.Add Name:=Replace(ws.Name & "_C1F", " ", "_"), RefersToR1C1:="=OFFSET(R3C7,0,0,R1C6,1)"
然后你相应改变其余部分。
或者,如果您希望每次运行代码时更改范围:
ws.Names.Add Name:=Replace(ws.Name & "_C1F", " ", "_"), RefersToR1C1:="=OFFSET(R3C7,0,0,” & RowLength & " ,1)"
你做的地方
RowLength=range(“F1”).value
答案 1 :(得分:0)
仅针对第一个范围,请使用
ActiveWorkbook.Names.Add Name:=Replace(ws.Name & "_C1F", " ", "_") _
, RefersTo:="=offset($G$3,,,$F$1)" _
, MacroType:=1
进行类似的更改以设置其他动态范围。
MacroType:=1
表示名称确实引用了一个函数。