VBA excel:从多个文件复制特定的单元格和列

时间:2018-10-11 14:38:47

标签: excel vba excel-vba

我正在尝试将多个文件中的特定单元格和3列复制到另一个电子表格的单个列中。

称为“导入”的部分仅允许选择多个文件。 “数据复制”部分应复制所需的值。

Sub import()
Dim oFileDialog As FileDialog

    Set oFileDialog = Application.FileDialog(msoFileDialogFilePicker)
    oFileDialog.AllowMultiSelect = True
    oFileDialog.InitialFileName = "C:\Users\L18938\Desktop\New_folder"    ' can set your default directory here

    oFileDialog.Show

    Dim iCount As Integer
    For iCount = 1 To oFileDialog.SelectedItems.Count
        Call Datacopy(oFileDialog.SelectedItems(iCount))
    Next

End Sub

Public Function Datacopy(strPath As String)
Dim filePath As String
Dim FileNum As Integer

filePath = strPath

Dim startDate As String
If Range("A2").Value <> "" Then
    Range("A1").End(xlDown).Offset(1, 0).Select
Else:
    Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).Offset(1, 0).Select
End If
currentRow = 0
rowNumber = 0

Open filePath For Input As #1

'EOF(1) checks for the end of a file
Do Until EOF(1)

        If rowNumber = 0 Then
            startDate = lineitems(2)
        End If
        If rowNumber > 18 And item <> "" Then

                ActiveCell.Offset(currentRow, 0) = startDate
                ActiveCell.Offset(currentRow, 1) = lineitems(0)
                ActiveCell.Offset(currentRow, 2) = lineitems(1)
                ActiveCell.Offset(currentRow, 3) = lineitems(2)

                currentRow = currentRow + 1
            End If
        End If

    Next item
 rowNumber = rowNumber + 1
Loop
Close #1

End Function

当我运行它时,出现错误“子或函数未定义”。 我定位的单元格是: -C1->是要复制到A列中的每个文件中不同的日期 -A18:A,B18:B,C18:C->列分别是要复制到B,C,D列中的数据。

复制多个文件非常重要,因为我有180多个文件。 有什么帮助吗?预先谢谢你!

1 个答案:

答案 0 :(得分:0)

您的问题是“ startDate = lineitems(2)”。您的代码中没有任何东西可以为“ lineitems”分配任何类型的值。