更改运行宏的范围

时间:2016-09-19 13:05:05

标签: excel vba

有没有办法改变运行宏的范围?

例如,如果我有macro1

Public rng1 As Range
' ...
Set rng1 = Range("K10").Offset(i, 0)

我想使用macro2将位置更改为右边的1个单元格。

这样的事情:

Set rng1 = rng1.Offset(0, 1)

这可能还是有另一种方式?

整个代码:

Public rng1 As Range

Sub tert()

Dim rng As Range
Dim rnga As Range
Dim i As Integer
i = 0

Do
    DoEvents
    Set rng1 = Range("K10").Offset(i, 0)
    Set rng = Range("J10").Offset(i, 0)
    Set rnga = Union(rng, rng1)
    rng.Interior.ColorIndex = 3
    rng1.Interior.ColorIndex = 3
    rng.Offset(-4, 0).clear
    rng1.Offset(-1, 0).clear
    i = i + 1

    Application.Wait (Now + TimeValue("00:00:01"))

    If Not Intersect(Range("A30:Z30"), rnga) Is Nothing Then Exit Sub
    If rng.Offset(1, 0).Interior.ColorIndex = 3 Then Exit Sub

Loop

End Sub


Sub rightx()
    Set rng1 = rng1.Offset(0, 1)
End Sub

2 个答案:

答案 0 :(得分:1)

只是为了演示它是如何工作的:

Option Explicit

Sub DynamicRange()

Dim rng1    As Range
Dim i       As Long

' let's take 1 as the offset value
i = 1

Set rng1 = Range("K10").Offset(i, 0)
Debug.Print rng1.Address  ' << you get $K$11

Set rng1 = rng1.Offset(0, i)
Debug.Print rng1.Address  ' << you get $L$11    

End Sub

修改1 :将代码放在2个单独的Sub中,将rng1声明移到Sub之外,并将其声明为Public

Option Explicit

' moved the rng1 declaration outside the Sub and declared it as Publi
Public rng1    As Range

Sub Call2Macros()

Call DynamicRange
Call DynamicRange2

End Sub

Sub DynamicRange()

Dim i       As Long

i = 1
Set rng1 = Range("K10").Offset(i, 0)  
Debug.Print rng1.Address  ' << you get $K$11

End Sub

Sub DynamicRange2()

Dim i       As Long

i = 2
Set rng1 = rng1.Offset(0, i)
Debug.Print rng1.Address  ' << you get $M$11

End Sub

答案 1 :(得分:0)

这是一个基本的例子。通过在程序之外声明范围,可以使用模块中的任何子

Dim rng As Range

Sub test1()
    Dim i As Integer

    For i = 1 To 2
        Set rng = Range("K10").Offset(i, 0)
        Debug.Print rng.Address
        OffsetRange
        Debug.Print rng.Address
    Next i
End Sub

Sub OffsetRange()
    Set rng = rng.Offset(0, 1)
End Sub

这不是一个特别有用的代码 - 它所做的只是偏移和调试该位置。但是,它应该说明一种解决问题的方法