這是我一直在摔跤一段時間的問題。原諒我不引用我研究過的確切線索,但我沒有保留日誌。下面的代碼示例是通過查看有關此主題的許多主題構建的。但是,我需要的確切解決方案仍然是逃避我。如何識別excel中的分頁符與VBA,變化條件
簡而言之:在Excel VBA中,我需要能夠識別長表中每頁的最後一行和第一/最後一列,長表中可能有1到5頁長(水平)創建和填充。我還希望能夠快速確定填充數據停止的位置,但如果沒有簡單的解決方案,可以從生成例程中獲取。以下代碼將識別單個頁表的正確最終行和列......一次。我可以進行修改以檢查多頁表格的後續頁面。我遇到的真正問題是,一旦一個單元格被填充並清除,excel將包含所使用單元格範圍內的單元格。隨後執行此相同的代碼失敗,因爲最後一個單元不再被正確識別。無論如何要扭轉這一點,或者我可以採取不同的方法?
我真的不喜歡填充單元格並刪除它們來查找分頁符,但我還沒有找到避免這樣做的解決方案。感謝您提供的任何指導。 ,Mike Shanahan
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](http://www.cpearson.com/excel/LastCell.aspx) –
謝謝Yan F.我會研究這個函數。 –