【问题标题】:Excel.Shape throwing ArgumentExceptionExcel.Shape 抛出 ArgumentException
【发布时间】:2020-01-18 06:30:05
【问题描述】:

我有一个包含Excel.Shape 的类。

在我的一个函数中(允许将形状从一张纸移动到另一张纸),我有以下代码:

Private Property ThisShape As Excel.Shape

Public Property Sheet As Excel.Worksheet Implements IShapeWrapper.Sheet
    Get
        If Not Me.HasShape Then Return Nothing
        Return Me._Sheet
    End Get
    Set(value As Excel.Worksheet)

        If value Is Nothing Then Throw New ArgumentNullException(NameOf(value))
        If Not Me.HasShape Then Exit Property 'Throw New InvalidOperationException("Unable to assign sheet: This wrapper does not contain any shapes.")
        If value Is Me._Sheet Then Exit Property

        Try
            Dim TestShapeName As Excel.Shape = value.Shapes.Item(Me.ThisShape.Name)
            Throw New InvalidOperationException("The destination worksheet already contains a shape with the same name.")
        Catch ex As Exception
        End Try

        Me._Sheet = value

        VBMath.Randomize()
        Dim ShapeNamePrefix As String = $"AppName_{CInt(VBMath.Rnd() * 1000000)}_{Date.Now.Millisecond}_"
        Dim TempName As String = ShapeNamePrefix & Me.ThisShape.Name
        Me.ThisShape.Name = TempName
        Me.ThisShape.Cut()
        value.Paste()

        Me.ThisShape = Nothing
        For Each MyShape As Excel.Shape In value.Shapes
            If MyShape.Name = TempName Then
                Me.ThisShape = MyShape
                MyShape.Name = String.Concat(MyShape.Name.Skip(ShapeNamePrefix.Length))
                Exit For
            End If
        Next

        If Me.ThisShape Is Nothing Then Throw New ApplicationException("Unable to re-bind with shape after copy/pasting.")

    End Set
End Property
Private _Sheet As Excel.Worksheet

对于某些形状(实际上,总是相同的形状,这是我正在处理的 50 个形状之一),

MyShape.Name = String.Concat(MyShape.Name.Skip(ShapeNamePrefix.Length)) 抛出 MyShape

System.ArgumentException: 指定的值超出范围。

这很令人困惑,因为该行基本上是MyObject.Property = MyObject.Property & Something。调试时,我可以回显?MyShape.Name(反正刚刚在上面的代码中读取了两行)

我很困惑这个异常指的是什么(它无法通过索引定位形状吗?),以及为什么分配属性失败。

这是 VB.Net 代码,但我添加了 VBA 标签,因为我怀疑这是 Office.Interop API 问题。

【问题讨论】:

  • 与其他形状相比,一种形状有什么不同?
  • 我还没想通..!它们都被相同的对象包裹和操作..
  • 对于有效的形状和无效的形状,MyShape.Name 的实际字符串值是多少?
  • 如果ShapeNamePrefix.Length 大于MyShape.Name,您会收到该错误。调试这些值并查看此形状是否如此。相当于说,shp.Name = Mid("Sid", 6, 5) 在 VBA 中
  • 所有形状的长度相同(GUID 和关键字的混合)。问题解决了,因为那个特定的形状是Locked。有趣且令人困惑:究竟如何在锁定时复制/粘贴但不能重命名形状,out of range 如何转换为property is locked? ...

标签: vb.net vsto excel-interop


【解决方案1】:

如果形状受到保护,则可以通过编程方式移动它,但不能重命名。就像可以以编程方式更改受保护工作表的单元格内容一样,而合并/取消合并单元格需要取消保护工作表。

解决方法是取消选中形状属性中的protected 框(或通过Interop API),或者解锁工作表本身。

【讨论】:

    猜你喜欢
    • 2012-08-10
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 2021-12-01
    • 2010-10-17
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多