2016-10-10 14 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