如何使用Interop写入标签Excel对象属性

时间:2013-10-17 12:49:33

标签: vb.net excel vba

我正在转换一些使用Excel的vb.net代码,以使用MS提供的Excel interops(版本14)。我已成功地转换了大量代码,但我有最后一个问题,我无法设置Excel表单标签标题文本。 我正在使用Shapes而不是Pictures,我尝试使用Shapes.AddLabel做同样的事情,但我无法做到。

这是我使用COM对象的旧代码

With ExcelObject
    .ActiveSheet.OLEObjects.Add(ClassType:="Forms.Label.1", Link:=False,
    DisplayAsIcon:=False, Left:=iTempLeft, Top:=iTempTop,
    Width:=iTempWidth, Height:=iTempHeight).Select() 
    iLabels = iLabels + 1
    sLabelName = "Label" & CStr(iLabels)
    .ActiveSheet.OLEObjects(sLabelName).object.Caption = gudtDrawingAndDefectXYsForPrint(iDrawing).sDrawingName
    .ActiveSheet.OLEObjects(sLabelName).Placement = Microsoft.Office.Interop.Excel.XlPlacement.xlMoveAndSize 
End With

现在这是我尝试使用Interop

的更新代码
With ExcelObject
     CType(.ActiveSheet, Excel.Worksheet).Shapes.AddLabel(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, iTempLeft, iTempTop, iTempWidth, iTempHeight).Name = sLabelName
     CType(.ActiveSheet, Excel.Worksheet).Shapes.Item(sLabelName).Placement = Excel.XlPlacement.xlMoveAndSize
     CType(.ActiveSheet, Excel.Worksheet).Shapes.Item(sLabelName).Title = gudtDrawingAndDefectXYsForPrint(iDrawing).sDrawingName
End Width

标题不会在屏幕上显示任何内容,因为“标题”使用COM对象。

1 个答案:

答案 0 :(得分:2)

这对我有用。 (在VS 2010 Ultimate + Office 2010中测试

ACTIVEX CONTROLS

    Dim xlApp As New Excel.Application
    Dim xlWb As Excel.Workbook
    Dim xlsheet As Excel.Worksheet
    Dim oleObj As Excel.OLEObject

    With xlApp
        .Visible = True

        xlWb = .Workbooks.Add

        xlsheet = xlWb.Sheets("Sheet1")

        With xlsheet
            oleObj = .OLEObjects.Add(ClassType:="Forms.Label.1", Link:=False,
                    DisplayAsIcon:=False, Left:=200, Top:=100,
                    Width:=100, Height:=35)

            oleObj.Object.caption = "Sid"
        End With
    End With

FORM CONTROLS

    Dim xlApp As New Excel.Application
    Dim xlWb As Excel.Workbook
    Dim xlsheet As Excel.Worksheet
    Dim Shp As Excel.Shape

    With xlApp
        .Visible = True

        xlWb = .Workbooks.Add
        xlsheet = xlWb.Sheets("Sheet1")

        With xlsheet
            Shp = .Shapes.AddLabel(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, 513, 128, 90, 27)

            Shp.TextFrame2.TextRange.Text = "Sid"

        End With
    End With