循环VBA后被遗忘的variables值
我目前正试图设置一个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
在debugging模式下。 这个循环第一次执行所有预期的工作,我可以看到我的rng.Address是指定的单元格范围。 但是,在第二个循环rng.Address变成<ObjectRequired>
,所以脚本的其余部分失败。 任何想法如何永久设置rng.Address到指定的单元格范围?
很难说没有看到更多的代码是什么特定的问题,但我会build议一个更简洁的逻辑,而不是像这样:
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
closures了工作簿,那可能是在杀死对象的引用
任何想法如何永久设置
rng.Address
到指定的单元格范围?
是的,只保留Address
而不是对象 。 由于Address
是一个string文字,所以即使对象引用超出作用域,也可以将其保留在String
variables中:
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)
问题是,范围对象连接到第一个工作簿。 所以当您closures该工作簿时,范围对象将会丢失。
您需要将地址保存在stringvariables中 ,以便您可以在每个循环中访问它。
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
你需要在if语句之外声明该variables,在循环之外更好。 否则你不能在if / loop语句之外访问它。