【发布时间】:2020-01-28 18:12:37
【问题描述】:
这是我一直在努力解决的问题。请原谅我没有引用我研究过的确切线程,但我没有记录日志。我下面的代码示例是通过查看有关此主题的许多线程构建的。但是,我需要的确切解决方案仍然无法解决。
简单地说:在 Excel VBA 中,我需要能够在动态创建后识别长表中每一页的最后一行和第一/最后一列,该长表的长度可能为 1 到 5 页(水平)和人口稠密。我也很欣赏一种快速确定填充数据停止位置的方法,但如果没有简单的解决方案,可以从生成例程中获取。以下代码将识别单个页表的正确最后一行和一列......一次。我可以进行必要的修改以检查多页表的后续页面。我遇到的真正问题是,一旦填充并清除了一个单元格,excel就会将该单元格包含在已用单元格的范围内。相同代码的后续执行失败,因为不再正确识别最后一个单元格。有没有办法扭转这种情况,或者我可以采取不同的方法?
我真的不喜欢填充单元格并删除它们来查找分页符,但我还没有找到避免这样做的解决方案。感谢您提供的任何指导。 ,迈克·沙纳汉
Sub Findpagebreaks()
Dim x As HPageBreaks, pb_x As HPageBreak
Dim y As VPageBreaks, pb_y As VPageBreak, PageMatrix() As Integer
Dim LastPopulated(1) As Integer, test As Integer, target As Integer
ReDim PageMatrix(1 To 1, 0 To 2) As Integer
With ActiveSheet
Debug.Print "============================================"
Debug.Print "Horizontal Page Breaks"
Set x = .HPageBreaks
Debug.Print "Initial Hbreaks: ", x.Count
LastPopulated(0) = .Cells.SpecialCells(xlCellTypeLastCell).Row
Debug.Print "Last row of data: ", LastPopulated(0)
target = x.Count + 1
test = LastPopulated(0)
Do While x.Count < target
test = test + 10
.Cells(test, 1).Value = "."
Debug.Print "cell: " & .Cells(test, 1).Address & " populated"
If test > 100 Then Exit Do
Loop
For Each pb_x In x
If pb_x.Extent = xlPageBreakFull Then
Debug.Print "Row: " & pb_x.Location.Row, "Full Page Break"
PageMatrix(1, 2) = pb_x.Location.Row - 1
Else
Debug.Print "Row: " & pb_x.Location.Row, "Partial Page Break"
End If
Next pb_x
.Range(.Cells(LastPopulated(0) + 1, 1), .Cells(test, 1)).ClearContents
Debug.Print "cells: " & .Range(.Cells(LastPopulated(0), 1), .Cells(test, 1)).Address & " cleared."
Debug.Print "Horizontal Exploration complete."
Debug.Print "Vertical Page Breaks"
Set y = .VPageBreaks
Debug.Print "Initial vbreaks: ", y.Count
LastPopulated(1) = .Cells.SpecialCells(xlCellTypeLastCell).Column
Debug.Print "Last column of data: ", LastPopulated(1)
target = y.Count + 1
test = LastPopulated(1)
Do While y.Count < target
test = test + 10
.Cells(1, test).Value = "."
Debug.Print "cell: " & .Cells(1, test).Address & " populated"
If test > 100 Then Exit Do
Loop
PageMatrix(1, 0) = 1
For Each pb_y In y
If pb_y.Extent = xlPageBreakFull Then
Debug.Print "column: " & pb_y.Location.Column, "Full Page Break"
PageMatrix(1, 1) = pb_y.Location.Column - 1
Else
Debug.Print "Row: " & pb_y.Location.Column, "Partial Page Break"
End If
Next pb_y
.Range(.Cells(1, LastPopulated(1) + 1), .Cells(1, test)).ClearContents
Debug.Print "cells: " & .Range(.Cells(1, LastPopulated(1)), .Cells(1, test)).Address & " cleared."
Debug.Print "Vertical Exploration complete."
Debug.Print "Page", "First Col", "Last Col", "Last Row"
Debug.Print 1, PageMatrix(1, 0), PageMatrix(1, 1), PageMatrix(1, 2)
Debug.Print "~~~~~~~~~~~~~~~~~~~~~~"
Debug.Print "Sub complete."
Debug.Print
End With
End Sub
【问题讨论】:
-
xlCellTypeLastCell 不是您想要使用的。看看GetLastCell函数here
-
谢谢 Yan F。我会研究那个功能。