我们使用.net interop导出一组数据到Excel,我们的模板文件包含一些图像。
根据我们导出的列数量,我们希望根据图像大小/宽度将图像放在最后一列左侧的X像素位置。使用记录移动图像的宏功能是'no op'。设置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
'解决方案'
调试一段时间后,我们注意到这对我的办公室版本无效。将我的办公室版本更新到2010使上面的示例再次起作用。我们添加了另一个PictureShape来替换office 2007修复我们自己的问题。
答案 0 :(得分:3)
你确定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中创建了一个测试程序。实际上,下面的代码可以移动我的图像。
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
我怀疑您要么错误地指定形状,要么您希望它位于错误的位置,或者您保存不正确。
答案 1 :(得分:2)
也许这个链接很有用:
Moving images between cells in VBA
http://www.excelforum.com/excel-programming/679105-vba-inserting-selecting-moving-pictures.html
答案 2 :(得分:1)
一些Office 2013方法改变了它们的行为,以返回与Shape对象相对的ShapeRange对象。
您可能会收到错误,因为ShapeRange对象没有左侧属性(或顶部,右侧等)。您应该在调试器中确认这一点。
虽然它有点乱,你可以写这样的东西来保持你的代码兼容两个版本:
If TypeName(pic) = "ShapeRange" Then
Set pic = pic(1)
End If
这将拉动您在2013年寻找的对象,并将在2010年被忽略。