当行为空时复制到新工作表

时间:2013-08-08 20:20:37

标签: excel vba excel-vba excel-2010

问题

当我遇到一个空行时,我需要一个可以从sheet1复制到sheet [i]的宏。

示例数据

asdfasdf 1234
asdf 1234
gasdf 1234

asdf 1234 
asdf 1234 

fdas 1234
ds 1234

1234d 1234

RESULT

宏应该采用该样本数据并创建4个新表。每个分组都是自己的电子表格。

CODE

我对VBA有些新意,所以我并不总是低估代码,但我确实发现这个代码有点工作。我无法理解它足以让它发挥作用。

 Sub CreateNewWorksheets()
  Dim lLoop As Long, lLoopStop As Long
  Dim rMove As Range, wsNew As Worksheet

  Set rMove = ActiveSheet.UsedRange.Columns(1)
  lLoopStop = WorksheetFunction.CountIf(rMove, "Category")
  For lLoop = 1 To lLoopStop
  Set wsNew = Sheets.Add
  rMove.Find("Category", rMove.Cells(1, 1), xlValues, _
  xlPart, , xlNext, False).CurrentRegion.Cut _
  Destination:=wsNew.Cells(1, 1)
  wsNew.UsedRange.Columns.AutoFit
 Next lLoop
End Sub

和另一种解决方案......

'Split File up by blank sections
Application.ScreenUpdating = False
For Each c In ActiveSheet.Range("A:C").SpecialCells(xlCellTypeConstants).Areas
    c.Copy Destination:=Worksheets.Add(After:=Sheets(Sheets.Count)).Range("A1")
Next c

这些都不适合我。

提前致谢

1 个答案:

答案 0 :(得分:1)

尝试一下:

Sub CreateNewWorksheets()

    Dim rngStart As Range
    Dim rngEnd As Range

    Set rngStart = Range("A1")
    If Len(rngStart.Text) = 0 Then Set rngStart = rngStart.End(xlDown)

    Do
        Select Case (Len(rngStart.Offset(1).Text) = 0)
            Case True:  Set rngEnd = rngStart
            Case Else:  Set rngEnd = rngStart.End(xlDown)
        End Select
        Range(rngStart, rngEnd).EntireRow.Copy Sheets.Add(After:=Sheets(Sheets.Count)).Range("A1")
        Set rngStart = rngEnd.End(xlDown)
    Loop While rngStart.Row < Rows.Count

    Set rngStart = Nothing
    Set rngEnd = Nothing

End Sub