我使用 VBA 从模板创建工作表,然后为创建的每个工作表创建范围内的命名范围。每个命名范围对应于打印时为一页的打印区域。我还使用工作表索引为命名范围的每个工作表创建一个唯一的字符串,以便更容易排除故障,因为最多可能有 2000 个工作表。
Sub NewSheet()
Dim n As String, pr1 As String, pr2 As String, pr3 As String, NmSTR As String
Dim Print_Area_1 As Range, Print_Area_2 As Range, Print_Area_3 As Range
With ThisWorkbook
NmSTR = ActiveSheet.Name
n = ActiveSheet.Index
pr1 = "Print_Area_" & n & "1"
pr2 = "Print_Area_" & n & "2"
pr3 = "Print_Area_" & n & "3"
Set Print_Area_1 = Range("$A$1:$R$80")
Set Print_Area_2 = Range("$A$85:$R$164")
Set Print_Area_3 = Range("$A$170:$R$249")
Worksheets(NmSTR).Names.Add Name:=pr1, RefersTo:=Print_Area_1
Worksheets(NmSTR).Names.Add Name:=pr2, RefersTo:=Print_Area_2
Worksheets(NmSTR).Names.Add Name:=pr3, RefersTo:=Print_Area_3
End With
End Sub
由于该工作簿将通过平板电脑填写和打印(使用时宏将被禁用),因此我在单元格 AA1 中有一个公式,可以分析第二页或第三页上是否输入了任何内容,并返回 1、2、或 3 应使用打印区域公式中的哪个选项。我想在创建工作表时使用 VBA 代码将打印区域设置为以下公式,以便在输入信息时它可以在一周内更新。
=CHOOSE('Sheet1'!$AA$1,'Sheet1'!Print_Area_11,('Sheet1'!Print_Area_11,'Sheet1'!Print_Area_12),('Sheet1'!Print_Area_11,'Sheet1'!Print_Area_12,'Sheet1'!Print_Area_13))
我尝试添加以下VBA代码来设置打印区域,但结果是Print_Area_1的值
'Sheet1'!$A$1:$R$80
而不是公式。
With ActiveSheet.PageSetup
.PrintArea = "=CHOOSE('" & NmSTR & "'!$AA$1,'" & NmSTR & "'!" & pr1 & ",('" & NmSTR & "'!" & pr1 & ",'" & NmSTR & "'!" & pr2 & "),('" & NmSTR & "'!" & pr1 & ",'" & NmSTR & "'!" & pr2 & ",'" & NmSTR & "'!" & pr3 & "))"
End With
任何帮助将不胜感激。
我发现我解决这个问题的方法几乎走在正确的轨道上。虽然打印区域属性不允许将其设置为公式,但创建后,您可以使用 Names 对象的 .RefersToLocal 属性更改它以使其成为公式。
Sub NewSheet()
Dim n As String, pr1 As String, pr2 As String, pr3 As String, NmSTR As String
Dim Print_Area_1 As Range, Print_Area_2 As Range, Print_Area_3 As Range
With ThisWorkbook
NmSTR = ActiveSheet.Name
n = ActiveSheet.Index
pr1 = "Print_Area_" & n & "1"
pr2 = "Print_Area_" & n & "2"
pr3 = "Print_Area_" & n & "3"
Set Print_Area_1 = Range("$A$1:$R$80")
Set Print_Area_2 = Range("$A$85:$R$164")
Set Print_Area_3 = Range("$A$170:$R$249")
Worksheets(NmSTR).Names.Add Name:=pr1, RefersTo:=Print_Area_1
Worksheets(NmSTR).Names.Add Name:=pr2, RefersTo:=Print_Area_2
Worksheets(NmSTR).Names.Add Name:=pr3, RefersTo:=Print_Area_3
ActiveSheet.PageSetup.PrintArea = "$A$1"
ActiveSheet.Names("Print_Area").RefersToLocal = "=CHOOSE('" & NmSTR & "'!$AA$1,'" & NmSTR & "'!" & pr1 & ",('" & NmSTR & "'!" & pr1 & ",'" & NmSTR & "'!" & pr2 & "),('" & NmSTR & "'!" & pr1 & ",'" & NmSTR & "'!" & pr2 & ",'" & NmSTR & "'!" & pr3 & "))"
End With
End Sub