Cryptic code is fine for some. Especially when it works. In this case, if you have more than 9 checkboxes it won't work. Change snb's code as follows:
Sub M_snb()
For Each it In ActiveDocument.FormFields
If it.Type = 71 And it.Result Then FileCopy "C:\SourcePath\Filename" & Right(it.Name, Len(it.Name) - InStrRev(it.Name, "_")) & ".ext", "C:\DestPath\Filename" & Right(it.Name, Len(it.Name) - InStrRev(it.Name, "_")) & ".ext"
Next
End Sub
I suspect that you will never be graded of fined for you style of coding so you might as well write it so it makes sense to you. In my case,
I prefer to declare my variables and use variable names that relate (at least to me) to what they are. For example, a formfield is an object so I use "oFF."
In most cases, unless you are playing "I can write that code in XX characters or less, I don't see any point in using 71 over the constant wdFormFieldCheckBox. Yes, they both mean the same thing. But one is crystal clear to even a novice where the other is clear as mud. There are cases where you must use the numerical value. For example if you are writing code that will be run with Word 2010 and 2007 that involves content control checkboxes (constant wdContentControlCheckBox) then you "must" use the numerical value "8" in your code because the constant is not defined in the Word 2007 object model and would result in a error when the code is compiled.
Unconventional I suppose, but I indent my code with 2 spaces while it seems the vast majority of people use 4. To me, 4 just seems to result in too much white space and makes the code harder for me to read.
Unless the line is very short e.g., If oFF IsNothing Then Exit Sub, I typically use If, Then, End If format over the shorter If, Then
I try to handle potential errors.
I try to (but not always) to comment my code so I will make sense to me years later when I look at it again.
Just as a matter of style, I typically end my procedures with:
lbl_Exit:
Exit Sub
I won't try to defend it. It is just my style and sort of a QA check for myself that I've looked over the procedure.
Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
'Declare variables
Dim oFF As FormField
Dim strIndex As Long
For Each oFF In ActiveDocument.FormFields
'Is the field a checkbox? Is it checked?
If oFF.Type = wdFieldFormCheckBox And oFF.CheckBox.Value Then
'Get the numerical index of the checkbox. This is the number(s) after the "_"
strIndex = Right(oFF.Name, Len(oFF.Name) - InStrRev(oFF.Name, "_"))
'Handle errors
On Error GoTo Err_Handler
FileCopy "C:\SourcePath\Filename" & strIndex & ".ext", "C:\DestPath\Filename" & strIndex & ".ext"
End If
ReEntry:
Next oFF
lbl_Exit:
Exit Sub
Err_Handler:
MsgBox "Error (" & Err.Number & " - " & Err.Description & ") occurred while attempting" & vbCr _
& "to copy C:\SourcePath\Filename" & strIndex & ".ext"
Resume ReEntry
End Sub