我几天来一直在与这个代码作斗争,并希望得到一些关于我出错的指导。
我的项目是创建一个可打印的文档格式,其中包含制作说明和空格,供操作员编写手动输入,打印到A4时需要最小的单元格大小。这些说明将有所不同,但在所有情况下都将在B栏中签字,在某些情况下将进行会签。签名B列中的标记为“Op”,并且签名的标记为“Check”。
为了调整打印文档的单元格大小,我试图计算行高,直到固定总数(832),从那时起我希望代码上升并查找第一个“Op”,如果“Op”在下面的单元格中有一个“Check”,然后在“Check”下面插入一个分页符,如果没有,则在“Op”下面插入一个分页符。从那里我希望代码在每次总行数为832时继续到文档底部插入分页符。
我不确定这种方法是否最适合实现我的目标,但是我会很感激我对目前的内容有一些反馈,我在这段代码上得到了一个运行时错误1004,它正在插入分页符错误的地方。
Sub TotalHeight()
Dim HowTall As Long
Dim Count As Long
Dim TotalHeight As Long
HowTall = 0
Count = 0
TotalHeight = 0
Dim cell As Range
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'If Not cell.Hidden Then
HowTall = HowTall + cell.RowHeight
'Count = Count + 1
If HowTall > 832 Then
Debug.Print cell.Row
For tmpcounter = 0 To 100
' If (Range(cell.Row).Offset(-tmpcounter, 0).Value) = "Op" Then
If cell.Offset(-tmpcounter, 0).Value = "Op" Then
If cell.Offset(-tmpcounter + 1, 0).Value = "Check" Then
'Found Check - get current row
PageBreakRowNo = cell.Offset(-tmpcounter + 1, 0).Row
Debug.Print "Check found at row " & PageBreakRowNo
Sheets("Dispensary").HPageBreaks.Add Before:=cell.Offset(-tmpcounter + 2, 0)
Else
'Only found Op - Get current row
PageBreakRowNo = cell.Offset(-tmpcounter, 0).Row
Debug.Print "Op found at row " & PageBreakRowNo
Sheets("Dispensary").HPageBreaks.Add Before:=cell.Offset(-tmpcounter + 1, 0)
End If
End If
Next tmpcounter
End If ' end of of HowTall >832 loop
Next 'end of for each cell in Column B loop
End Sub
答案 0 :(得分:0)
在原始代码中添加了我建议的改进:
Sub TotalHeight()
Dim HowTall As Long
Dim Count As Long
Dim TotalHeight As Long
Dim tmpcounter1 As Long
HowTall = 0
Count = 0
TotalHeight = 0
Dim cell As Range
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'If Not cell.Hidden Then
HowTall = HowTall + cell.RowHeight
'Count = Count + 1
If HowTall > 832 Then
Debug.Print cell.Row
For tmpcounter = 0 To 100
If cell.Offset(-tmpcounter, 0).Value = "Op" Or cell.Offset(-tmpcounter, 0).Value = "Check" Then
PageBreakRowNo = cell.Offset(-tmpcounter + 1, 0).Row
tmpcounter1 = tmpcounter
Debug.Print "Op / Check found at row " & PageBreakRowNo
Sheets("Dispensary").HPageBreaks.Add Before:=cell.Offset(-tmpcounter + 2, 0)
Exit for 'to stop looking upwards
End If
Next tmpcounter
HowTall = 0 'reset HowTall to start again for the next page
For i = tmpcounter1 +1 to 0 Step -1 'Calculate the HowTall lost due to stepping back
HowTall = HowTall + cell.Offset(i,0).RowHeight
Next i
End If ' end of of HowTall >832 loop
Next 'end of for each cell in Column B loop
End Sub