因此,您有一个良好的开端来尝试处理您的数据。我有一些技巧要分享,希望能帮助你更接近。 (请在您完成工作时回来提出更多问题!)
首先,尝试avoid using Select or Activate in your code。当您查看录制的宏时,我知道您看到的就是这些。但这是您的击键和鼠标点击(选择和激活)的记录。您可以在没有它的情况下访问单元格或区域中的数据(请参见下面的示例)。
为了处理您的数据,您的第一个问题是确定数据集的开始位置(哪一行)和结束位置。通常,您的数据位于具有 BOLD 数据的单元格之间。例外是最后一个数据集,它只有许多空白行(直到列的末尾)。因此,我创建了一个从给定行开始的函数,并检查其下方的每一行以查找粗体单元格或数据末尾。
Private Function EndRowOfDataSet(ByRef ws As Worksheet, _
ByVal startRow As Long, _
Optional maxRowsInDataSet As Long = 50) As Long
'--- checks each row below the starting row for either a BOLD cell
' or, if no BOLD cells are detected, returns the last row of data
Dim checkCell As Range
Set checkCell = ws.Cells(startRow, 1) 'assumes column "A"
Dim i As Long
For i = startRow To maxRowsInDataSet
If ws.Cells(startRow, 1).Font.Bold Then
EndRowOfDataSet = i - 1
Exit Function
End If
Next i
'--- if we make it here, we haven't found a BOLD cell, so
' find the last row of data
EndRowOfDataSet = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
End Function
为了向您展示如何将其用于您的特定数据,我创建了一个测试子例程,指示如何遍历所有不同的数据集:
Option Explicit
Public Sub DataBetween()
Dim thisWB As Workbook
Dim dataWS As Worksheet
Set thisWB = ThisWorkbook
Set dataWS = thisWB.Sheets("YourNameOfSheetWithData")
'--- find the first bold cell...
'Dim nextBoldCell As Range
'Set nextBoldCell = FindNextBoldInColumn(dataWS.Range("A1"))
'--- now note the start of the data and find the next bold cell
Dim startOfDataRow As Long
Dim endOfDataRow As Long
Dim lastRowOfAllData As Long
startOfDataRow = 3
lastRowOfAllData = dataWS.Cells(ws.Rows.Count, "A").End(xlUp).Row
'--- this loop is for all the data sets...
Loop
endOfDataRow = EndRowOfDataSet(dataWS, startOfDataRow)
'--- this loop is to work through one data set
For i = startOfDataRow To endOfDataRow
'--- work through each of the data rows and copy your
' data over to the other sheet here
Next i
startOfDataRow = endOfDataRow + 1
Do While endOfDataRow < lastRowOfAllData
End Sub
同时使用这两种方法,看看是否能让您更接近完整的解决方案。
编辑:我应该删除那段代码。这是我早期的一个概念,但它并没有完全奏效。我注释掉了这些行(为了以后在阅读 cmets 时更清楚)。下面,我将介绍该功能以及为什么它不能完全适用于这种情况。
所以这是有问题的函数:
Public Function FindNextBoldInColumn(ByRef startCell As Range, _
Optional columnNumber As Long = 1) As Range
'--- beginning at the startCell row, this function check each
' lower row in the same column and stops when it encounters
' a BOLD font setting
Dim checkCell As Range
Set checkCell = startCell
Do While Not checkCell.Font.Bold
Set checkCell = checkCell.Offset(1, 0)
If checkCell.Row = checkCell.Parent.Rows.Count Then
'--- we've reached the end of the column, so
' return nothing
Set FindNextBoldInColumn = Nothing
Exit Function
End If
Loop
Set FindNextBoldInColumn = checkCell
End Function
现在,虽然这个函数工作得很好,但情况是不考虑最后一个数据集的结尾。换句话说,像这样的情况:
在这种情况下,函数FindNextBoldInColumn 将返回nothing,而不是数据的结尾。所以我(应该完全)删除了该功能并用 EndRowOfDataSet 替换它,这正是你所需要的。对此感到抱歉。