2016-10-10 13 views
1

我一直在试图解决这个问题一段时间。以下代码将您选择的图片插入到我的Excel文档中。它将图片放在单元格B10中,并将其大小调整到我合并单元格的高度。现在的问题是我无法将其置于中心位置。合并单元格中的VBA中心图片

.Left = 35# 

随着上面的行我可以手动中心一张图片,但我希望其他每张图片与其他宽度的中心以及。任何人都可以帮我解决这个问题吗?下面的代码是我一直在使用的。提前致谢!

Sub Insert_Pic_Section_One() 

Dim fileName1 As Variant 

fileName1 = Application.GetOpenFilename(filefilter:="Tiff Files(*.tif;*.tiff),*.tif;*.tiff,JPEG Files (*.jpg;*.jpeg;*.jfif;*.jpe),*.jpg;*.jpeg;*.jfif;*.jpe,Bitmap Files(*.bmp),*.bmp", FilterIndex:=2, Title:="Choose picture", MultiSelect:=False) 

If fileName1 = False Then 
Exit Sub 
Else 
ActiveWorkbook.ActiveSheet.Select 
Range("B10").Select 
Dim picture1 As Object 
Set picture1 = ActiveWorkbook.ActiveSheet.Pictures.Insert(fileName1) 

    With picture1 
    .Top = .Top 
    .Left = 35# 
    .Width = .Width 
    .Height = 233# 
    End With 

End If 

End Sub 
+1

中心关于什么?你是怎么想出35的?这听起来像每个图片的算术应该这样做。 – arcadeprecinct

回答

0

无需选择任何东西。因为您使用合并的单元格,所以您需要使用.MergeArea,否则它只会提供未合并的行和列的高度和宽度。

Dim ws As Worksheet 
Dim targetCell As Range 
Dim picture1 As Picture 

Set ws = ActiveSheet 'replace with actual worksheet if possible 
Set targetCell = ws.Range("B10") 
Set picture1 = ws.Pictures.Insert(fileName1) 

With picture1 
    .Height = targetCell.MergeArea.Height 'set height first because width will change 
    .Top = targetCell.Top 
    .Left = targetCell.Left + (targetCell.MergeArea.Width - .Width)/2 
End With 
+0

非常感谢,这工作! –

+0

@SjoerdEeman然后你可以接受答案;) – arcadeprecinct