如何创建宏来拆分列和行?

时间:2017-12-27 11:14:04

标签: arrays vba excel-vba rows excel

我有一个包含3列的长工作表:

A栏=发票编号
B列=接收金额
C栏 - 支付金额

A栏中的每个数字都需要拆分为两行:付款和接收 对于Pay,将从C列中获取员工编号 对于接收,将从B列获取员工编号

Test excel

2 个答案:

答案 0 :(得分:1)

假设您的数据位于Sheet1,我们会将分割后的数据放在Sheet2中。这是一个简单的解决方案:

Sub Split_Column()

Set st1 = ThisWorkbook.Sheets("Sheet1")
Set st2 = ThisWorkbook.Sheets("Sheet2")

j = 1
For i = 1 To st1.UsedRange.Rows.Count

    st2.Cells(j, 1) = st1.Cells(i, 1)
    st2.Cells(j, 2) = "Pay"
    st2.Cells(j, 3) = st1.Cells(i, 3)
    j = j + 1
    st2.Cells(j, 1) = st1.Cells(i, 1)
    st2.Cells(j, 2) = "Receive"
    st2.Cells(j, 3) = st1.Cells(i, 2)
    j = j + 1

Next

End Sub

答案 1 :(得分:0)

我已经创建了简单的VBA代码,将行分割为Activeworkbook的sheet1到sheet2的列。您可以根据需要修改代码。

Dim sel As Range, b As Range
Dim rcount As Integer: rcount = 1
ActiveWorkbook.Sheets(2).Range("A:C").Delete Shift:=xlDown
With ActiveWorkbook.Sheets(1)
Set sel = .Range("A2:C" & .UsedRange.Rows.Count)
For Each b In sel.Rows
ActiveWorkbook.Sheets(2).Cells(rcount, 1).Value = b.Value2(1, 1)
ActiveWorkbook.Sheets(2).Cells(rcount, 2).Value = .Cells(1, 2).Value
ActiveWorkbook.Sheets(2).Cells(rcount, 3).Value = b.Value2(1, 2)
ActiveWorkbook.Sheets(2).Cells(rcount + 1, 1).Value = b.Value2(1, 1)
ActiveWorkbook.Sheets(2).Cells(rcount + 1, 2).Value = .Cells(1, 3).Value
ActiveWorkbook.Sheets(2).Cells(rcount + 1, 3).Value = b.Value2(1, 3)
rcount = rcount + 2
Next
End With