简体   繁体   English

合并单元格中的VBA中心图片

[英]VBA Center picture in merged cells

I've been trying to fix this problem for a while.我一直试图解决这个问题一段时间。 The following code inserts a picture from your choose to my excel document.以下代码将您选择的图片插入到我的 excel 文档中。 It places the picture in cell B10 and resizes it to the height of one of my merged cells.它将图片放在单元格 B10 中并将其大小调整为我合并的单元格之一的高度。 Now the problem is that I can't get it centerd.现在的问题是我无法让它居中。

.Left = 35# 

With the line above i can manually center one picture, but i want every other picture with other width's to be centerd aswell.使用上面的行,我可以手动将一张图片居中,但我希望其他宽度的所有其他图片也居中。 Can anyone help me with this problem?谁能帮我解决这个问题? The code below is what i've been using.下面的代码是我一直在使用的。 Thanks in advance!提前致谢!

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

No need to select anything.无需选择任何内容。 Because you use a merged cell you need to use .MergeArea otherwise it will only give you the height and width of the unmerged row and column.因为您使用合并单元格,所以您需要使用.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM