【问题标题】:VBA excel: Copy specific cells and columns from multiple filesVBA excel:从多个文件中复制特定的单元格和列
【发布时间】:2020-07-02 21:05:53
【问题描述】:

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

名为“导入”的部分只允许选择多个文件。 “Datacopy”部分应复制所需的值。

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 个。

【问题讨论】:

  • 哪一行报错?
  • 你在哪一行得到错误?是Open filePath For Input As #1,因为看起来应该是评论
  • Public Function Datacopy(strPath As String) 顺便说一句,还有一部分调用“item”可能会出错,因为它没有定义(代码来自另一个工作)

标签: excel vba


【解决方案1】:

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

【讨论】:

  • 这是有道理的...它曾经在我删除的部分中,因为我使用此代码对 csv 文件执行相同的工作,但这是一个正常的 xlsx,所以我删除了逗号分隔的部分。
  • 不,我使用了另一个适合 xlsx 文件而不是 csv 的代码 :)
猜你喜欢
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
相关资源
最近更新 更多