未使用页脚的格式化代码和页面方向数据不匹配

我有一个工作表(adHoc)单元格b28包含的位置

(10)&“&D&T”&Chr(10)&“Version 1.0”&Chr(10)&“&F 2014”

当我使用上述更新另一个工作簿中另一个工作表的页脚时。 我没有得到embedded的格式 – 它显示了什么是包含在单元格b28.例如,Excel应该看到&9并使字体9点。

我也收到页面方向的数据types不匹配错误。 单元格b36的内容是xlLandscape

上周我在另一块板上贴了一个这个问题的副本,但没有得到任何答案。 我希望这里有人有答案。

http://www.mrexcel.com/forum/excel-questions/919033-updating-pagesetup-using-cells-master-worksheet-orientation-formatting-footer-excel-visual-basic-applications.html

这是我正在使用的代码。

Sub page_setup() Dim reportWB As Excel.Workbook Dim sheet As Excel.Worksheet 'open report workbook - name of workbook is in cell b4 Set reportWB = Workbooks.Open(Workbooks("macros.xlsm").Sheets("adHoc").Range("b4").Value) Dim leftFooter leftFooter = Workbooks("macros.xlsm").Sheets("adHoc").Range("b28").Value For Each sheet In reportWB.Sheets With sheet .PageSetup.leftFooter = leftFooter .PageSetup.Orientation = Workbooks("macros.xlsm").Sheets("adHoc").Range("b36").Value End With Next End Sub 

阅读你的页脚定义,就像他们被视为文字string,而不是代码。 您需要以某种方式将代码parsing为有效的页脚string。

对于LeftFooterstring,您可以使用Evaluate来解决它,但是它需要被写入,就好像它是一个Excel公式,而不是VBA,所以使用

(10)&“&D&T”&Char(10)&“Version 1.0”&Char(10)&“&F 2014”年度至今财务数据

请注意,我使用的是Char而不是Chr ,Excel公式相当于。

对于方向,你正在使用一个命名的常量,这将无法正常工作。 将值放在Excel工作表上(在这种情况下为2 ),或者编写自己的代码来将名称parsing为其值

工作版本(如上所述,修正了源数据)

 Sub page_setup() Dim reportWB As Excel.Workbook Dim sheet As Excel.Worksheet Dim wsSource As Worksheet 'open report workbook - name of workbook is in cell b4 Set wsSource = Workbooks("macros.xlsm").Sheets("adHoc") Set reportWB = Workbooks.Open(wsSource.Range("b4").Value) Dim leftFooter leftFooter = wsSource.Range("b28").Value For Each sheet In reportWB.Sheets With sheet .PageSetup.leftFooter = Evaluate(leftFooter) .PageSetup.Orientation = wsSource.Range("b36").Value End With Next End Sub 

要处理常量,您可以添加一个UDF,将string名称parsing为值,并从您的设置表调用该值

例如

 Function GetConst(s As String) As Variant Select Case s Case "xlLandscape" GetConst = xlLandscape Case "xlPortrait" GetConst = xlPortrait ' etc End Select End Function 

放入单元格B36 GetConst("xlLandscape") (作为一个string,而不是公式),并将您的方向代码行更改为

 .PageSetup.Orientation = Evaluate(wsSource.Range("b36").Value) 

将所需的其他任何常量添加到Select Case语句中。

AFAIK,没有(简单)的方法来做你想做的事情。 当您将代码放在单元格中,然后调用该单元格的值代替实际的代码时,VBA试图运行的不是:

.PageSetup.Orientation = xlLandscape

反而:

.PageSetup.Orientation = "xlLandscape"

这会产生你所看到的错误和行为。

作为经验法则,如果您的VBA代码需要一个string(即“”)或数字中的某个字符,您可以在表单上进行计算并将代码拉入该值。

对于一切(有万事达卡)把它放在代码中。 例如:

leftfooter = cell1.value & Chr(10) & cell2.value & Chr(10) & cell3.value

(作为一个侧面说明,我不熟悉格式,似乎你想要做的string…这些通常是通过像

 With sheet.PageSetup.leftFooter. .Font.Size = 9 'etc...