简体   繁体   English

Excel VBA从HDD向我的WorkSheets上的CenterHeader添加图片(1)

[英]Excel VBA Adding picture from HDD to my CenterHeader on my WorkSheets(1)

I have trouble making my VBA code work for the Center Header on the top of the page in Excel. 我在使Excel页面顶部的Center Header的VBA代码无法工作时遇到麻烦。 I want it to load a picture (of my choosing) to the header. 我希望它将(我选择的)图片加载到标题中。

It works for cell "C2", which my code currently works for, but I can't figure out how to get it to put the picture to the header instead of cell "C2". 它适用于单元格“ C2”,我的代码当前适用于该单元格,但是我不知道如何获取图片以将图片放置到标题而不是单元格“ C2”。

My code is as follows (and it chooses the right picture I want to add by comparing the names and paths on the harddrive to an drop-down list. The script/code/macro is automaticly activated when I change type in the drop-down list): 我的代码如下(通过将硬盘驱动器上的名称和路径与下拉列表进行比较,它选择了我想要添加的图片。当我在下拉列表中更改类型时,脚本/代码/宏会自动激活清单):

Private Sub Worksheet_Change(ByVal Target As Range)

Dim myPict As Picture
Dim PictureLoc As String

If Target.Address = Range("A2").Address Then

ActiveSheet.Pictures.Delete

PictureLoc = "K:\MyPictures\" & Range("A2").Value & ".png"

With Range("C2")
    Set myPict = ActiveSheet.Pictures.Insert(PictureLoc)
    myPict.Top = .Top
    myPict.Left = .Left
    myPict.ShapeRange.LockAspectRatio = msoTrue
    myPict.ShapeRange.Width = 157
    myPict.ShapeRange.Height = 18
    myPict.Placement = xlMoveAndSize
End With

End If

End Sub

Any suggestions? 有什么建议么?

Thanks 谢谢

You need to access the PageSetup object like this: 您需要像这样访问PageSetup对象:

With ActiveSheet.PageSetup
    .CentertHeaderPicture.Filename = PictureLoc
    .CenterHeader = "&G"
End With

To access the header of a worksheet (every worksheet is done seperate) use the PageSetup property of the worksheet object. 若要访问工作表的标题(每个工作表都单独完成),请使用工作表对象的PageSetup属性。 Official MS Documentation 官方MS文档

There you can change the CenterHeaderPicture: 您可以在其中更改CenterHeaderPicture:

Example Code from Microsoft Documentation Microsoft文档中的示例代码

Sub InsertPicture() 

 With ActiveSheet.PageSetup.CentertHeaderPicture 
 .FileName = "C:\Sample.jpg" 
 .Height = 275.25 
 .Width = 463.5 
 .Brightness = 0.36 
 .ColorType = msoPictureGrayscale 
 .Contrast = 0.39 
 .CropBottom = -14.4 
 .CropLeft = -28.8 
 .CropRight = -14.4 
 .CropTop = 21.6 
 End With 

 ' Enable the image to show up in the center header. 
 ActiveSheet.PageSetup.CenterHeader = "&G" 

End Sub

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

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