使用Excel创建导入文件的最佳方法?

时间:2015-04-14 16:12:38

标签: excel vba excel-vba

不确定描述这种情况的最佳方式是什么,但我会尽我所能。我正在尝试使用Excel为数据库系统创建导入文件。

以下是我们的例子:

1) Names in a Column
2) Accounts in a Column (Accounts 1-3)
3) Amounts (An Amount for each Combo, ex: Name1, Account1, Name 1, Account2)

那么我想要的是一种简单的方法(可能使用VBA?)来创建类似于下面的导入文件:

(Columns A, B, C)
Name#1, Account#1, Amount#1
Name#1, Account#2, Amount#2
Name#1, Account#3, Amount#3
Name#2, Account#1, Amount#4
Name#2, Account#2, Amount#5
etc.. etc..

无论如何,无需进行大量的复制和粘贴就可以做到这一点吗?我尝试了数据透视表,但它似乎并不适合我的情况

示例数据:

Names     |  Accounts   |   Amounts
David        11230          $32.50
Marry        11240          $2.00
Jerry        54500          $990.00
             64000          $500.00
                            $300.00
                            $600.00
                            $330.55
                            $500.00
                            $45.00
                            $53.38
                            $75.00
                            $44.00

因此我们想要的输出是:

David, 11230, $32.50
David, 11240, $2.00
David, 54500, $990.00
David, 64000, $500.00
Marry, 11230, $300.00
Marry, 11240, $600.00
....Continue...

希望有所帮助

1 个答案:

答案 0 :(得分:1)

这对我有用:

Sub tester()

    Dim sht As Worksheet, rngNames As Range, rngAccts As Range
    Dim nm As Range, acct As Range, i As Long

    Set sht = ActiveSheet

    With sht
        Set rngNames = .Range(.Range("A2"), _
                          .Cells(.Rows.Count, 1).End(xlUp))
        Set rngAccts = .Range(.Range("B2"), _
                          .Cells(.Rows.Count, 2).End(xlUp))
    End With

    i = 1

    For Each nm In rngNames.Cells
    For Each acct In rngAccts.Cells
        i = i + 1
        sht.Cells(i, 5).Value = nm.Value
        sht.Cells(i, 6).Value = acct.Value
        sht.Cells(i, 7).Value = sht.Range("C1").Offset(i - 1, 0).Value
    Next acct
    Next nm

End Sub

输入在ColA-C中,输出到Cols E-G