Excel宏:用于循环文件到文件

时间:2011-10-28 19:35:35

标签: excel vba excel-vba

我不知道VBA但我需要编写一个宏来优化我的工作。 我正在寻找我的代码来遍历文件并将每个文件中的相同列复制/粘贴到excel工作簿上(逐列)。这是我到目前为止(注意我把“i”放在文件名中):

Sub NewMacro()

For i = 0 To 99

    Workbooks.OpenText Filename:= _
        "C:\User\Folder\file_up000i.txt", _
        Origin:=932, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
        Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
        TrailingMinusNumbers:=True
    Range("A3").Select
    Selection.Copy
    With ActiveWindow
        .Top = 6.25
        .Left = 53.5
    End With
    Windows("Book1").Activate
    With ActiveWindow
        .Top = 40.75
        .Left = 13
    End With
    Range("B1").Select
    ActiveSheet.Paste
    Windows("file_up000i.txt").Activate
    Range("C26").Select
    Range(Selection, Selection.End(xlDown)).Select
    Application.CutCopyMode = False
    Selection.Copy
    Windows("Book1").Activate
    Range("B2").Select
    ActiveSheet.Paste
    Windows("file_up000i.txt").Activate
    With ActiveWindow
        .Top = 4
        .Left = -75.5
    End With
    ActiveWindow.Close

    Next i

End Sub

显然这不起作用,但我不知道怎么回事。非常感谢你的帮助!

1 个答案:

答案 0 :(得分:3)

假设您的文件名为file_up0000.txtfile_up0001.txt ... file_up0099.txt这里是您宏的重构

Sub NewMacro()
    Dim i As Long
    Dim shTxt As Worksheet
    Dim shDest As Worksheet
    Dim TxtName As String

    Set shDest = ActiveSheet
    For i = 0 To 99
        TxtName = "file_up" & Format(i, "0000")
        Workbooks.OpenText Filename:= _
            "C:\User\Folder\" & TxtName & ".txt", _
            Origin:=932, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
            xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
            Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
            TrailingMinusNumbers:=True

        Set shTxt = Workbooks(TxtName & ".txt").Worksheets(TxtName)

        shTxt.[A3].Copy shDest.[B1]
        shTxt.Range(shTxt.[C26], shTxt.Range("C26").End(xlDown)).Copy shDest.[B2]
        shTxt.Parent.Close False
    Next i

End Sub