如何使用Windows窗体应用程序中的Excel函数LoadPicture()

时间:2016-10-24 14:20:54

标签: vb.net vba excel-vba visual-studio-2010 windows-forms-designer

我有一个Windows表单应用程序,我的公司用它来访问它的所有报告。大多数报告都是在运行时从头开始创建的Excel工作表或Excel模板中提供给用户的。到目前为止,这一切都很好。我现在遇到的问题是我需要在Excel模板上加载ImageBox,并在驱动器上保存图像。我有图像的文件路径(这将在每次运行时更改)。我发现能够设置ImageBox的图片属性的唯一方法就是这样......

Dim FileStr As String = "C:\Folder\ImageFile.jpg"

xlWorksheet.ImageName.Picture = LoadPicture(FileStr)

问题是我无法弄清楚如何从windows窗体中调用LoadPicture()函数。我知道我可以在运行时创建一个调用LoadPicture()然后将其删除的Excel模块,但我只是认为必须有更好的方法吗?希望有人在那里有建议。谢谢。 编辑: - 这是我用来打开Excel表格的代码示例

Imports ExcelVB = Microsoft.Office.Interop.Excel
Imports ad = GartnerInterface.AdminClass.AdminTools
Imports xl = GartnerInterface.AdminClass.XlHelp

Public Class TestClass

    Public Shared Sub NewSub()

        Dim xlApp As ExcelVB.Application
        Dim xlWorkbook As ExcelVB.Workbook
        Dim xlWorksheet As ExcelVB.Worksheet

        Dim TestSht As String

        TestSht = "H:\Josh\ExcelTest.xlsm"

        xlApp = CreateObject("Excel.Application")
        xlWorkbook = xlApp.Workbooks.Add(TestSht)
        xlApp.DisplayAlerts = False
        xlApp.Visible = True
        xlWorksheet = xlApp.Sheets("Sheet1")

        Dim FileStr As String = "H:\12117\12117_Original.png"
        'xlWorksheet.RFQImg.Picture = LoadPicture(FileStr)

    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

现在我正在查看代码,您可能需要.AddPicture方法

在此代码的底部,您需要以下内容:

Dim FileStr As String = "H:\12117\12117_Original.png"
xlWorksheet.Shapes.AddPicture(FileStr, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45)

取自, https://msdn.microsoft.com/en-us/library/office/ff198302.aspx

或者,如果您有一个模板,其中图像已经命名为“test”

Dim FileStr As String = "H:\12117\12117_Original.png"
Dim imgName as String = "test"
For Each myShape In xlWorksheet.Shapes
    If myShape.Name = imgName then        
       cTop = myShape.ShapeRange.Top 'we must save the values here
       cLeft = myShape.ShapeRange.Left
       cHeight = myShape.ShapeRange.Height
       cWidth = myShape.ShapeRange.Width
       myShape.delete
       Exit For
     end if            
next
xlWorksheet.Shapes.AddPicture(FileStr, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, cLeft, cTop, cWidth, cHeight)

An example, with user interaction, I borrowed from