组合多个工作表的VBA代码大多数都有效,但却产生了意想不到的结果

时间:2014-10-08 01:44:25

标签: excel vba excel-vba

场景:工作簿将具有可变数量的工作表,每个工作表都具有可变数量的填充单元格,最常见于列A但不一定。没有标题行。我想将所有工作表组合成一个“主”工作表,之后我将执行各种恶作剧。我所拥有的“大部分”都有效,但由于某种原因,它将第1行留空,这是我不想要的。我想我可以删除空行,但这看起来非常俗气,并没有解决潜在的问题,这是我不明白它为什么这样做。

代码:

Private Sub cmdFinalize_Click()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim final As Worksheet
    Dim rng As Range
    Dim colCount As Integer

    Set wb = ActiveWorkbook

    Set final = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
    final.Name = "Final"
    Set ws = wb.Worksheets(1)
    colCount = ws.Cells(1, 255).End(xlToLeft).Column

    For Each ws In wb.Worksheets
        If ws.Index = wb.Worksheets.Count Then
            Exit For
        End If
        Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(65536, 1).End(xlUp).Resize(, colCount))
        final.Cells(65536, 1).End(xlUp).Offset(1).Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
    Next ws
End Sub

我认为Offset(1)导致了问题,但是完全删除它会导致每个工作表的 last 行项被下一个工作表的第一行覆盖一起在'主'工作表上。

1 个答案:

答案 0 :(得分:0)

您只需要在工作表之后和之后使用offset(1)。

以下代码使用一个标志来指示处理工作表是否是第一个。

Private Sub cmdFinalize_Click()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim final As Worksheet
    Dim rng As Range
    Dim colCount As Integer

    Dim firstWorksheetFlag as boolean  'Flag to indicate the first worksheet is in process
    firstWorksheetFlag = True          ' Flag is true at begin

    Set wb = ActiveWorkbook

    Set final = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
    final.Name = "Final"
    Set ws = wb.Worksheets(1)
    colCount = ws.Cells(1, 255).End(xlToLeft).Column

    For Each ws In wb.Worksheets
        If ws.Index = wb.Worksheets.Count Then
            Exit For
        End If
        Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(65536, 1).End(xlUp).Resize(, colCount))
        If firstWorksheetFlag 'Offset(1) is not used.
            final.Cells(65536, 1).End(xlUp).Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
            firstWorksheetFlag = False ' first worksheet has been processed, so next is not first.
        Else 'second or later worksheet, so Offset(1) is used.
            final.Cells(65536, 1).End(xlUp).Offset(1).Resize(rng.Rows.Count,rng.Columns.Count).Value = rng.Value
        End If
    Next ws
End Sub