Excel互动移动/设置图像位置

我们使用.net interop将一组数据导出到Excel,并且我们的模板文件包含一些图像。

根据我们要导出的列的数量,我们希望根据图像大小/宽度将图像放在最后一列左侧X像素的位置。 使用这个logging一个移动图像的macros函数是一个“不操作”。 设置Shape.Left位置也不起作用。

这个问题

如何使用单元格中剩下的互操作X像素或者X / Y是相对于单元格的像素位置的固定X / Y位置在Excel中定位图像。

这没有奏效

Dim pixels As Integer = 40 Dim cell As Excel.Range = ws.Cells(10, 10) s.Left = s.Left - 100 

解决scheme'

经过一段时间的debugging,我们注意到这在我的办公室版本中不起作用。 更新我的办公室版本到2010年,使上面的例子再次工作。 我们添加了另一个PictureShapereplaceOffice 2007修复我们自己的问题。

你确定Shape.Left是行不通的吗? 如果正确,它工作正常。 试试像这样(C#):

 //This assumes shape is already assigned to the shape you want to move //and ws is assigned to the worksheet //set cell to whatever cell you want to move the image to Excel.Range cell = ws.Cells[10, 10]; int pixels = 40; //Number of extra pixels over from the left edge of the cell shape.Left = ((float)cell.Left + pixels); shape.Top = ((float)cell.Top); 

要vb它应该是像下面的东西,但我不是一个vb专家

 Dim pixels As Integer = 40 Dim cell As Excel.Range = ws.Cells(10, 10) s.Left = (CSng(cell.Left) + pixels) 'Note: if using cell.Left you must cast as single s.Top = CSng(cell.Top) 

编辑:我刚刚在VB中创build一个testing程序。 下面的代码实际上是移动我的图像。

  Dim oXL As Excel.Application Dim oWB As Excel.Workbook Dim oSheet As Excel.Worksheet Dim oRng As Excel.Range Dim oShape As Excel.Shape ' Start Excel and get Application object. oXL = CreateObject("Excel.Application") oXL.Visible = True ' Get a new workbook. oWB = oXL.Workbooks.Open("*insert_valid_path_here*") oSheet = oWB.ActiveSheet For Each oShape In oSheet.Shapes oShape.Left = oShape.Left + 9000 Next ' Make sure Excel is visible and give the user control ' of Excel's lifetime. oXL.Visible = True oXL.UserControl = True ' Make sure that you release object references. oRng = Nothing oSheet = Nothing oWB = Nothing oXL.Quit() oXL = Nothing 

我怀疑你是不正确地分配形状,或者你期望它在错误的位置,或者你保存不正确。

一些Office 2013方法更改其行为以返回与Shape对象相反的ShapeRange对象。

你可能会得到错误,因为ShapeRange对象没有左边的属性(或顶部,右边等等)。 你应该在debugging器中确认这一点。

虽然有点麻烦,但你可以写下这样的代码来保持你的代码兼容版本:

 If TypeName(pic) = "ShapeRange" Then Set pic = pic(1) End If 

这将拉动你在2013年寻找的对象,2010年将被忽略。