Word宏编译报错:Invalid use of property 问题排查求助
Fixing the "Invalid use of property" Error in Your Word Macro
First off, let's break down why you're hitting that compile error. In VBA, when you're assigning object variables (like a Row object from a Word table), you can't just use a plain equals sign—you need to use the Set keyword. That's exactly what's tripping up this line:
targetRows(UBound(targetRows)) = oRow
Since Row is an object, VBA sees this as an invalid attempt to use a property instead of assigning the object reference correctly.
Here's the corrected version of your macro:
Sub TableCleaner() ' ' TableCleaner Macro ' Dim objTable As Table Dim sourceDocument As Document Set sourceDocument = ActiveDocument Dim UserChoice As String Dim QuestionToMessageBox As String QuestionToMessageBox = "Delete row with Text?" Dim targetRows() As Row Dim rowCount As Integer rowCount = 0 For Each oRow In sourceDocument.Tables(1).Rows UserChoice = MsgBox(oRow.Cells(1).Range.Text, vbYesNo, "Delete Row?") If UserChoice = vbYes Then rowCount = rowCount + 1 ' Resize the array only when we have a new row to add ReDim Preserve targetRows(1 To rowCount) As Row Set targetRows(rowCount) = oRow ' Use Set for object assignment oRow.Shading.BackgroundPatternColor = Word.WdColor.wdColorLightGreen End If Next oRow ' Only show confirmation if there are rows to delete If rowCount > 0 Then Confirmation = MsgBox("Are you sure you want to delete " & rowCount & " rows?", vbYesNo, "Confirm?") If Confirmation = vbYes Then ' Loop backwards through the array to avoid skipping rows during deletion For i = rowCount To 1 Step -1 targetRows(i).Delete Next i End If Else MsgBox "No rows selected for deletion.", vbInformation, "Info" End If End Sub
Key improvements I made:
- Added the
Setkeyword when assigning theRowobject to the array (this fixes the core compile error) - Used a
rowCountvariable to track selected rows—this eliminates the empty array element that would have caused errors during deletion - Changed the deletion loop to run backwards (from last selected row to first) because deleting rows top-to-bottom shifts remaining rows up, which can lead to skipping rows if you loop forwards
- Added a check to show a message if no rows were selected, making the macro more user-friendly
Quick reminder:
When working with object collections in VBA (like Rows in a Word table), always use Set when assigning individual objects to variables or array elements. It's a common gotcha for folks new to VBA macros!
内容的提问来源于stack exchange,提问作者Shahzeb Khan
相关产品推荐
相关产品推荐

