循环VBA后忘记变量值

ale*_*ef2 2 excel vba excel-vba

我目前正在尝试建立一个Do While循环,其中循环的一部分只执行一次.我正在有效地尝试为一个工作表定义单元格范围,然后让我的循环将相同的单元格范围应用于所有工作表/工作簿,而无需重新指定范围.

这是我到目前为止:

isExecuted = False
Do While FileName <> ""
    ' Open a workbook in the folder
    Set WorkBk = Workbooks.Open(Folder & "\" & FileName)

        ' Conditional to select range only once
        If Not isExecuted Then

            Dim rng As Range
            Set rng = Application.InputBox("Select a Range", "Obtain Range Object", Type:=8)
            Debug.Print (rng.Address)
            MsgBox "The cells selected were " & rng.Address
            isExecuted = True

        End If


    Set SourceRange = WorkBk.Worksheets(1).Range(rng.Address)

' more stuff goes here
Run Code Online (Sandbox Code Playgroud)

在调试模式下.第一次执行此循环时,一切都按预期工作,我可以看到我的rng.Address是指定的单元格范围.但是,在第二个循环中,rng.Address成为<ObjectRequired>,因此脚本的其余部分失败.有关如何将rng.Address永久设置为指定单元格范围的任何想法?

Dav*_*ens 7

很难说没有看到更多代码的具体问题是什么,但我会建议一个更简洁的逻辑,而不是这样:

    If Not isExecuted Then

        Dim rng As Range
        Set rng = Application.InputBox("Select a Range", "Obtain Range Object", Type:=8)
        Debug.Print (rng.Address)
        MsgBox "The cells selected were " & rng.Address
        isExecuted = True

    End If
Run Code Online (Sandbox Code Playgroud)

做这个:

If rng is Nothing Then
    Set rng = Application.InputBox("Select a Range", "Obtain Range Object", Type:=8)
End If
Run Code Online (Sandbox Code Playgroud)

注意:如果您在' more stuff goes here部件期间关闭工作簿,那可能会杀死对范围的对象引用

有关如何永久设置rng.Address到指定单元格范围的任何想法?

是的,只保留Address而不是对象.由于Address是字符串文字,String即使对象引用超出范围,您也可以将其保留在变量中:

Dim addr As String
If addr = vbNullString
    addr = Application.InputBox("Select a Range", "Obtain Range Object", Type:=8).Address
End If
Set SourceRange = WorkBk.Worksheets(1).Range(addr)
Run Code Online (Sandbox Code Playgroud)