excel-vba – VBA宏 – 为生成的数据指定新工作表

目前我有一段代码可以开始和结束日期,并列出该日期范围内的所有日期.这允许我采取下表并将其拆分为各个日期.

|Name            | StartDate  | EndDate
|Bob The builder | 20/05/2015 | 24/05/2015 
|Tiny Tim        | 08/06/2015 | 09/06/2015
|Dolly Parton    | 06/08/2015 | 08/08/2015

但是,目前它将创建的数据直接转储到现有表下面,如下所示:

|Name            | StartDate  | EndDate
|Bob The builder | 20/05/2015 | 24/05/2015 
|Tiny Tim        | 08/06/2015 | 09/06/2015
|Dolly Parton    | 06/08/2015 | 08/08/2015
|Bob The builder | 20/05/2015 | 
|Bob The builder | 21/05/2015 |
|Bob The builder | 22/05/2015 | 
|Bob The builder | 23/05/2015 | 
|Bob The builder | 24/05/2015 | 
|Tiny Tim        | 08/06/2015 | 
|Tiny Tim        | 09/06/2015 | 
|Dolly Parton    | 06/08/2015 | 
|Dolly Parton    | 07/08/2015 |
|Dolly Parton    | 08/08/2015 |

我已经尝试了几种尝试让它在新工作表上找到它的方法,每次我用代码搞砸都失败了.另请注意,复制生成的数据将不起作用,因为每次运行此宏时,原始表将具有不同的行数.这是我一直在使用的代码:

Sub SeparateDateRange()

Dim Ws As Worksheet
Dim nCol As Integer


Set Ws = ActiveSheet

nCol = 1 

Application.ScreenUpdating = False


For i = 1 To ActiveSheet.Cells(Rows.Count, nCol + 2).End(xlUp).Row - 1 Step 1 

    For j = 0 To Ws.Cells(i + 1, nCol + 2).Value - Ws.Cells(i + 1, nCol + 1).Value Step 1 

  With Ws.Cells(Ws.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1)
    For k = 0 To nCol - 1 Step 1
        .Offset(0, k).Value = Ws.Cells(i + 1, k + 1).Value
    Next k

    .Offset(0, nCol).Value = DateSerial(Year(Ws.Cells(i + 1, nCol + 1).Value), Month(Ws.Cells(i + 1, nCol + 1).Value), Day(Ws.Cells(i + 1, nCol + 1).Value) + j)
    End With

    Next j
Next i

Application.ScreenUpdating = True

End Sub

最佳答案 您遇到的问题来自于您将生成的值放在Ws的偏移处,您已将其定义为活动工作表Set Ws = ActiveSheet

这反映在这里:

With Ws.Cells(Ws.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1)
For k = 0 To nCol - 1 Step 1
    .Offset(0, k).Value = Ws.Cells(i + 1, k + 1).Value
Next k

    .Offset(0, nCol).Value = DateSerial(Year(Ws.Cells(i + 1, nCol + 1).Value), Month(Ws.Cells(i + 1, nCol + 1).Value), Day(Ws.Cells(i + 1, nCol + 1).Value) + j)
End With   

而不是使用活动工作表,定义一个新工作表以插入值并在您的With中引用它,例如:

Dim newWS as worksheet
Set newWS = Sheets("SheetName")

With newWS.Cells(newWS.Cells(newWS.Rows.Count, 1).End(xlUp).Row + 1, 1)

这应该会让你走上正轨.

点赞