Word 2016 VBA For循环无法运行:代码异常问题求助
Let’s break down the issues with your For loop step by step—there are a few syntax and logic problems that are preventing it from running correctly, plus some edge cases you might not have considered:
Syntax Error: Invalid
Else Ifand Incomplete Code
VBA requiresElseIf(no space between the words) instead ofElse If. Your code cuts off atElse If b = T...which is a broken statement—this will cause a compile error before the loop even starts executing. The VBA editor should highlight this as a red flag immediately.Incorrect
MsgBoxHandling
Your lineIf vbOK Then Exit Subdoesn’t work as intended.vbOKis just a constant with a value of 1, so this condition will always evaluate toTrue—meaning your subroutine will exit right after any message box pops up, no matter what the user clicks. You need to capture the return value ofMsgBoxproperly:If MsgBox("Please do error 1!", vbOKOnly) = vbOK Then Exit SubPotential Loop Boundary Issue
Your loop starts ati = 6—ifActiveDocument.Tables(2).Rows.Countis less than 6, the loop will never run at all. Add a quick check before the loop to verify the row count meets your requirement:Dim tbl As Table Set tbl = ActiveDocument.Tables(2) If tbl.Rows.Count < 6 Then MsgBox "Table has fewer than 6 rows—loop won't execute." Exit Sub End IfUnchecked Table Existence
If your document doesn’t have a second table (Tables(2)), accessing it will throw a runtime error that stops the entire subroutine. Always validate that the table exists first:If ActiveDocument.Tables.Count < 2 Then MsgBox "Document doesn't have a second table." Exit Sub End IfInefficient Table Access
RepeatingActiveDocument.Tables(2)every time you access a cell or content control is slow and prone to typos. Assign the table to a variable once at the start of your subroutine, then use that variable throughout the loop.
Corrected Code Snippet
Here’s a cleaned-up version of your code that fixes these issues and adds safeguards:
Sub CheckTableRows() Dim tbl As Table Dim i As Long Dim z As Long, x As Long Dim b As Boolean ' Validate second table exists If ActiveDocument.Tables.Count < 2 Then MsgBox "Document doesn't have a second table." Exit Sub End If Set tbl = ActiveDocument.Tables(2) ' Validate table has enough rows for the loop If tbl.Rows.Count < 6 Then MsgBox "Table has fewer than 6 rows—no rows to check." Exit Sub End If For i = 6 To tbl.Rows.Count ' Calculate cell content lengths (minus 2 to exclude cell end markers) z = Len(tbl.Cell(i, 2).Range.Text) - 2 x = Len(tbl.Cell(i, 3).Range.Text) - 2 ' Check if content control shows placeholder text b = tbl.Cell(i, 5).Range.ContentControls.Item(1).ShowingPlaceholderText If z = 0 And x = 0 Then If b = True Then If MsgBox("Please do error 1!", vbOKOnly) = vbOK Then Exit Sub End If Else If MsgBox("Please do error 2!", vbOKOnly) = vbOK Then Exit Sub End If ' Add your incomplete ElseIf logic here once you finalize it Next i End Sub
内容的提问来源于stack exchange,提问作者MistF

