从阵列中打开文件

时间:2019-01-21 10:01:07

标签: arrays excel vba

我写了一个代码,希望用户选择多个文件,这些文件将循环通过。

我无法正确定义名称,因此无法使循环正常工作。

Sub RFPDataimporttest() 'select multiple files
    Dim Files As Workbook
    Dim Fname As Variant
    Dim SrcWbk As Workbook
    Dim DestWbk As Workbook
    Dim i As Integer

    Set DestWbk = ThisWorkbook
    'choose files and define them as array
    Fname = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Select alla RFP filer från leverantörer", MultiSelect:=True)
    If IsArray(Fname) Then
        For i = LBound(Fname) To UBound(Fname)

            'this where i have a problem. how do i open each file in an array?
            Set SrcWbk = Workbooks.Open(Fname)

            SrcWbk.Sheets("1. General Information").Range("L8").Copy
            With DestWbk.Worksheets("Sheet1").Cells(2, Columns.Count).End(xlToLeft).Offset(-1, 1)
               .PasteSpecial Paste:=xlPasteColumnWidths
               .PasteSpecial Paste:=xlPasteValues
            End With

            SrcWbk.Sheets("2. Product information").Range("Z1:AB91").Copy
            With DestWbk.Worksheets("Sheet1").Cells(2, Columns.Count).End(xlToLeft).Offset(0, 1)
                .PasteSpecial Paste:=xlPasteColumnWidths
                .PasteSpecial Paste:=xlPasteValues
            End With

            SrcWbk.Close False

        Next i
    End If

End Sub

1 个答案:

答案 0 :(得分:3)

结果是一个数组-您已经在检查该数组并对其进行循环。只需使用i作为索引:

  Set SrcWbk = Workbooks.Open(Fname(i))

(请注意,当用户仅选择一个文件时,结果甚至是一个数组,因此代码也适用于这种情况)