循环文件名并合并选择文件

时间:2015-04-22 19:05:22

标签: excel vba excel-vba

所以我对VBA很陌生,现在已经三天撞到墙上了。

在Sheet4中,我在C列中有一个文件名列表,在H列中有一个“文件类型”(即生产,测试等)。然后是具有各种文件类型的组合框。

我需要能够从组合框中选择文件类型,然后将所有文件类型的文件合并到不同的选项卡上进行审核。

下面是我到目前为止所拥有的代码,但它已经完全混乱了,而且我已经陷入困境了。

Sub MergeFiles()

    Dim rw As Long
    Dim strSourcePath As String
    Dim strFile As String
    Dim FileName As String
    Dim FileType As String
    Dim SelectedType As String
    Dim r As Long
    Dim strData As String
    Dim FI As Worksheet
    Dim Wkst As Worksheet
    Dim LastRow As String

    ' Folder path where files to be merged are located
    strSourcePath = Sheet1.TextBox1.Text

    If Right(strSourcePath, 1) <> "\" Then strSourcePath = strSourcePath & "\"

    rw = 9  'row number with first file name
    Set FI = Worksheets("FileInfo")
    FileName = FI.Cells(rw, "C").Text
    FileType = FI.Cells(rw, "H")
    SelectedType = Sheet4.ComboBox1.Text
    strFile = Dir(strSourcePath & FileName)

    Application.ScreenUpdating = False

    If Len(FileName) = 0 Then Exit Sub

Do Until strFile = ""
    If FileType <> SelectedType Then
        rw = rw + 1
        FileName = FI.Cells(rw, "C").Text
        FileType = FI.Cells(rw, "H")
    ElseIf FileType = SelectedType Then
        Workbooks.Open FileName:=strSourcePath & FileName
        ActiveSheet.Range("A1", ActiveCell.SpecialCells(xlLastCell)).Copy
        Workbooks("Quest PSC Data Review take2").Activate
        Worksheets("FileInfo").Activate
        LastRow = FI.Cells(Rows.Count, "B").End(xlUp).Row + 1
        Range("A", LastRow).Select
        Selection.PasteSpecial
        rw = rw + 1
        FileName = FI.Cells(rw, "C").Text
        FileType = FI.Cells(rw, "H")
    End If
Loop

0 个答案:

没有答案