向此宏添加另一个常量/列?

时间:2016-03-30 20:05:48

标签: excel vba excel-vba

现在这样做是什么,输入列A:E并添加你在F列中列出的任何内容,在它的末尾,保持A:E不变。这使得它更容易而不是复制和粘贴,但我想添加另一行,以便A:F是常量,将列表切换到G列。

例如,一旦输出,

A1,B1,C1,D1,E1,F1
A1,B1,C1,D1,E1,F2
A1,B1,C1,D1,E1,F3
etc.

我只想添加另一列来实现它

A1,B1,C1,D1,E1,F1,G1
A1,B1,C1,D1,E1,F1,G2
A1,B1,C1,D1,E1,F1,G3

这是我到目前为止所做的。

Dim LastRowIput As String
    With Sheets("Input")
    LastRowInput = .Cells(.Rows.Count, "C").End(xlUp).Row
    End With


For I = 2 To LastRowInput

Dim LastRowLoc As String
    With Sheets("Output")
    LastRowLoc = .Cells(.Rows.Count, "F").End(xlUp).Row + 1
    End With


    Sheets("Input").Select
    Range("F2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets("Output").Select
    Range("F" & LastRowLoc).Select
    ActiveSheet.Paste
    Sheets("Input").Select
    Range("A" & I & ":" & "E" & I).Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Output").Select

    Dim LastRow As String
    With ActiveSheet
    LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row + 1
    End With

    Range("A" & LastRow).Select
    ActiveSheet.Paste

    Dim LastRowLoc2 As String
    With Sheets("Output")
    LastRowLoc2 = .Cells(.Rows.Count, "F").End(xlUp).Row
    End With

    Application.CutCopyMode = False
    Range("A" & LastRow & ":" & "E" & LastRowLoc2).Select
    Selection.FillDown

    Sheets("Input").Select

Next I

1 个答案:

答案 0 :(得分:0)

似乎您想要将A:G中的行从输入复制到输出,在输出中为G中的每一行扩展A:F.

Dim i As Long, lastRowInput As Long, nextRowOutput As Long
Dim wso As Worksheet

Set wso = Worksheets("Output")

With Sheets("Input")
    lastRowInput = .Cells(.Rows.Count, "C").End(xlUp).Row

    For i = 2 To lastRowInput
        nextRowOutput = wso.Cells(.Rows.Count, "G").End(xlUp).Row + 1
        .Range(.Cells(2, "G"), .Cells(2, "G").End(xlDown)).Copy _
          Destination:=wso.Cells(nextRowOutput, "G")
        .Range("A" & i & ":" & "F" & i).Copy _
          Destination:=wso.Range(wso.Cells(nextRowOutput, "A"), _
                                 wso.Cells(wso.Cells(.Rows.Count, "G").End(xlUp).Row, "F"))
    Next i
End With

我已删除涉及Range .SelectRange .Activate方法的所有方法,转而使用直接引用。

Input_Sample_Data
输入工作表中的示例数据

Input_Sample_Data_expanded_to_Output
输出工作表中的示例结果