使用ShapeRange在Excel中调整注释大小

时间:2012-10-19 15:17:21

标签: c# excel comexception

我有一个以编程方式创建的电子表格,其中包含大量注释(最多40,000个)。从工作表中删除多个列后,注释会调整大小。这显然是excel中的一个错误。 (http://answers.microsoft.com/en-us/office/forum/office_2007-excel/excel-comment-boxes-resizing-themselves-andor/3fdf3e72-6ca5-4186-a656-b7b6fd8db781?msgId=d55534a5-4603-482e-ac97-9ec260124f78

理想情况下,我希望在删除列后立即自动调整所有注释。

试图避免遍历每个评论,这是我到目前为止所尝试的内容。

  • 设置AutoShapeDefaults无效 - 删除列后评论仍会调整大小。
  • XlPlacement属性。 XlMove和XLMoveAndSize无效。
  • 无论评论数量多少,Worksheet.Shapes.SelectAll都会抛出OutOfMemory异常

我的想法是获取电子表格中所有注释的ShapeRange对象,并从那里设置大小。

这非常有效:

        public static void ResizeComments()
        {
        Microsoft.Office.Interop.Excel.Workbook objWorkbook;
        objWorkbook = (Workbook)Globals.ThisAddIn.Application.ActiveWorkbook;
        Worksheet objSheet = (Worksheet)objWorkbook.ActiveSheet;

        int[] test = {1,2,3,4,5};
        ShapeRange sRange = objSheet.Shapes.Range[test];
        sRange.Height = 100;
        sRange.Width = 220;
        }

更改为此会在AutoSize行引发异常“来自HRESULT的异常:0x800A03EC”。

        ShapeRange sRange = objSheet.Shapes.Range[test];
        sRange.TextFrame.AutoSize = true;

使用我实际的Shape Indices数组会抛出相同的异常,但是在 Shapes.Range [] 。 我在调试时查看了 shapes 变量,它与 test 相同,只不过它是 int [249] 而不是 int [5] ] ;

        int[] shapes = (int[])shapes.ToArray(typeof(int)); 
        ShapeRange sRange = objSheet.Shapes.Range[shapes];

1 个答案:

答案 0 :(得分:1)

我将回答必须在Excel中的模块中运行的VBA代码。从讨论和回答here

Sub CommentFixer()
Dim Arng As Range, Acl As Variant, InitRng As Variant, MaxSize
Set InitRng = Selection
Set Arng = Application.InputBox("Select Ranges", , , , , , , 8)

For Each Acl In Arng
    If (Not (Acl.Comment Is Nothing)) And (Acl.MergeArea.Count = 1) Then
        Acl.Select
        Selection.Comment.Visible = True
        Selection.Comment.Shape.TextFrame.AutoSize = True
        'Commented as is obsolete if no further processing is needed  
        'Selection.Comment.Shape.Select
        'Commented not to fix Comment Aspect Ratio
        'With Selection.ShapeRange       'Fix 2.5 aspect ratio
        '    .LockAspectRatio = msoFalse
        '    MaxSize = .Width / 2.5
        '    If MaxSize > .Height Then
        '        .Height = MaxSize
        '    Else
        '        .Width = .Height * 2.5
        '    End If
        'End With
        'Commented to neglect fonts
        'With Selection.Font
        '    .Bold = False
        '    .Name = "Times New Roman"
        '    .Size = 12
        'End With

        Acl.Comment.Visible = False
    End If
Next
InitRng.Select

End Sub

保留代码和评论项目不需要。我仍然需要补偿无法处理的合并单元格。

欢呼声