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

时间:2015-06-03 19:44:21

标签: excel-vba vba excel

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

|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

1 个答案:

答案 0 :(得分:2)

您遇到的问题来自于您将生成的值设置为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) 中引用它:

namespace MyExtensions
{
    public static class HighPrecendenceExtensions
    {
        public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this IEnumerable<TSource> source)
        {
            return source;
        }
    }

    namespace LowerPrecedenceNamespace
    {
        public static class LowPrecedenceExtensions
        {
            public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this TSource source)
            {
                return new[] { source };
            }
        }
    }
}

这应该会让你走上正轨。