The original code is:
Public Sub VARTOFORM()
Dim i
For Each ctl In Automatiza.Controls
If TypeName(ctl) = "TextBox" Or TypeName(ctl) = "ComboBox" Then
Dim sName As Variant
sName = ctl.name ' Nome do controle no form
Next ctl
End Sub
After refactor:
Public Sub VARTOFORM()
Dim i
For Each
### **Dim ctl As Variant** '<====== Inserted By Rubberduck will generate error
ctl In Automatiza.Controls
If TypeName(ctl) = "TextBox" Or TypeName(ctl) = "ComboBox" Then
Dim sName As Variant
sName = ctl.name ' Nome do controle no form
Next ctl
End Sub
Version 2.2.0.3505
OS: Microsoft Windows NT 10.0.17134.0, x64
Host Product: Microsoft Office 2016 x64
Host Version: 16.0.4717.1000
Host Executable: WINWORD.EXE
Dim statements aren't executable, they won't generate an error unless the declared variable is used before the logical line that declares them; being inside a loop body makes no difference, no scope is smaller than procedure scope in VBA.
Rubberduck means to insert a declaration immediately above the first use... but definitely not in the middle of a For Each statement. How did that happen....
Repro confirmed from "introduce local variable" quickfix for "undeclared variable" inspection.
The culprit is line 26 of IntroduceLocalVariableQuickFix.cs:
_state.GetRewriter(result.Target).InsertBefore(result.Target.Context.Start.TokenIndex, instruction);
result.Target is the undeclared identifier; inserting the declaration immediately before Context.Start.TokenIndex is assuming that the result is located at the beginning of an instruction - we need to locate the preceding NEWLINE token, and insert before that position*.
I think it simply needs to insert before 'GetAncestor