循环VBA后忘记变量值

时间:2017-08-30 13:05:16

标签: 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

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

3 个答案:

答案 0 :(得分: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

这样做:

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

注意:如果您在' 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)

答案 1 :(得分:4)

问题是,Range对象是否连接到第一个工作簿。因此,当您关闭该工作簿时,Range对象将丢失。

您需要在字符串变量中保存地址,以便您可以在每个循环上访问它。

    Dim strAddress as String
    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
                strAddress = rng.Address
                isExecuted = True

            End If


        Set SourceRange = WorkBk.Worksheets(1).Range(strAddress )

    ' more stuff goes here

答案 2 :(得分:-3)

您需要在if语句之外声明变量,更好地在循环之外。否则你无法在if / loop语句之外访问它。