You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Set keyword when assigning the Row object to the array (this fixes the core compile error)
  • Used a rowCount variable 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:56:22