gpt4 book ai didi

Excel VBA 中心页眉/页脚 "Align Left"

转载 作者:行者123 更新时间:2023-12-04 20:28:53 30 4
gpt4 key购买 nike

有没有办法在 Excel 中对齐中心标题?我知道没有任何内置解决方案,但是否有任何 VBA 代码可以工作。我一直在尝试将单元格复制到标题,使用 VBA 设置中心标题,但我的中心标题一直是“对齐中心”。

我什至发现了非常复杂的代码来计算句子的长度并为每一行添加空格,但它并不能真正正常工作。

我还可以将行设置为在顶部重复而忘记页眉,但是页脚呢?如何设置中心页脚以对齐我的两行文本以左对齐?

我努力了:

With ActiveSheet.PageSetup
.LeftHeader = Range("a1").Value & " " & Range("b1").Value & " " & Range("a2").Value & " " & Range("b2").Value
End With

还将命名范围发送到标题:
Option Explicit

Sub SetCenterHeader()
Dim txt As String
Dim myRow As Range

With Range("NorthHead") ' reference named range
For Each myRow In .Rows ' loop through referenced range rows
txt = txt & Join(Application.Transpose(Application.Transpose(myRow.Value)), " ") & vbLf ' update 'txt' with current row cells values joined and separated by a blank
Next
End With
ActiveSheet.PageSetup.CenterHeader = Left(txt, Len(txt) - 1) ' set CenterHeader with resulting 'txt' excluding last vblf character
ActiveWindow.SelectedSheets.PrintOut Copies:=1
End Sub

结果总是一样的:

enter image description here

最佳答案

可以尝试以下解决方法并根据您的要求进行修改

Sub test2()
Dim CenHd1 As String, CenHd2 As String, Fname As String
Dim Rng As Range
Dim Sht As Worksheet, MnSht As Worksheet
Dim Cht As ChartObject

Set Sht = ThisWorkbook.Worksheets(3)
Set MnSht = ThisWorkbook.Worksheets(1)
Set Rng = Sht.Range("F1:F2")
CenHd1 = "Excel"
CenHd2 = "I am already left Aligned"
Sht.Range("F1").Value = CenHd1
Sht.Range("F2").Value = CenHd2
Sht.Activate
ActiveWindow.DisplayGridlines = False
With Rng
.Columns.AutoFit 'added after taking trial snapshot to perfectly center and left align
.HorizontalAlignment = xlLeft
.Font.Name = "Bookman Old Style"
.Font.Size = 12
'May specify other visual effects
End With
Rng.CopyPicture xlScreen, xlPicture

Set Cht = Sht.ChartObjects.Add(0, 0, Rng.Width * 1.01, Rng.Height * 1.01)
Cht.Name = "TmpChart"
Sht.Shapes("TmpChart").Line.Visible = msoFalse
Cht.Chart.Paste

Fname = "C:\Users\user\Desktop\CentHead " & Format(Now, "dd-mm-yy hh-mm-ss") & ".jpg"
Cht.Chart.Export Filename:=Fname, Filtername:="JPG"
DoEvents
Cht.Delete
ActiveWindow.DisplayGridlines = True

MnSht.Activate
With MnSht.PageSetup.CenterHeaderPicture
.Filename = Fname
'.Height = 275.25
'.Width = 463.5
'.Brightness = 0.36
'.ColorType = msoPictureGrayscale
'.Contrast = 0.39
'.CropBottom = 0
'.CropLeft = 0
'.CropRight = 0
'.CropTop = 0
End With

'Enable the image to show up in the center header.
MnSht.PageSetup.CenterHeader = "&G"
'for Trial only
ActiveWindow.View = xlPageLayoutView
' Clear junk files
If Dir(Fname) <> "" Then Kill (Fname)
End Sub

尝试如下
enter image description here

代码也可以修改为带有参数的函数/过程,以便与不同的工作表、工作簿等重复使用。希望它有助于达到目的。

关于Excel VBA 中心页眉/页脚 "Align Left",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682601/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com