1

我是 VBA 新手,我正在尝试编写一个代码,该代码将从多个 csv 文件中复制以下数据,这些文件都存储在同一目录中。

我需要它来打开每个 csv 文件

检查 H 到 CA 列中的 IF 行 8 中是否有任何值为 =“TotalLMP”的单元格(示例:单元格 H8 =“TotalLMP”)

然后将第 7 行和第 19 行的值复制到两个新列中(示例:SINCE H8="TotalLMP", COPY H7="100" AS COLUMN A, COPY H19 = "26.437" 作为 B 列)

然后将单元格 $A$9 中的值复制到第三列(示例:COPY A9="20100101" AS COLUMN C")

完成循环遍历每个 csv 文件后,关闭并转到下一个

然后在空白 excel 文件中的新活动工作表中将存储每个值,如下所示:

........A ......................B ......C

1 .. 100 .... 26.437 .... 20100101

2 .. 200 .... 26.585 .... 20100101

4

1 回答 1

3

让我暂时帮助您处理 CSV 循环,因为这对初学者来说相当困难。我相信您会弄清楚如何测试第 8 行中的值。如果没有,您可以随时寻求更多帮助!

为此,您必须使用 Microsoft Scripting Runtime。

我建议将您要打开的所有 csv 文件放在同一个目录中,并且只放置那些可以避免潜在问题的文件。

打开一个新工作簿并转到 VBE (ALT + F11)。创建一个新模块。单击这个新模块,然后转到工具 > 参考 > Microsoft 脚本运行时。这会让它知道它必须使用该模块及其对象。

将工作簿另存为启用宏的工作簿(.xls 或 .xslm 用于较新版本)与 CSV 相同的目录(或其他地方......)

然后开始编码:

Sub Import_all_Csv()
' Reference Needed: Microsoft Scripting Runtime

' Dim some pointers to know what objects you will be manipulating thereafter
Dim MyWs, CSV As Worksheet
Set MyWs = ActiveSheet ' Meaning you will have to run the macro from the spreadsheet you want to export to. Feel free to replace that
Dim wbCSV As Workbook

' Those are the objects that belong to the reference Microsoft Scripting Runtime
Dim oFSO As FileSystemObject
Dim oFld As Folder
Dim oFile As File

Dim File As String

' Initialize the FileSystemObject
Set oFSO = New FileSystemObject

' That will only work on windows so I'm adding an error handler to ignore it if need be
On Error Resume Next
ChDir ThisWorkbook.Path
On Error GoTo 0 ' I'm asking VBA to throw an error now

' Dialog box to select the first csv file (this will let you choose another directory everytime)
File = Application.GetOpenFilename("Comma Separated Values File (*.csv*), *.csv*")
If File = "False" Then
    Exit Sub ' Quit the macro if user canceled
Else
    ' Else get the path of the parent folder of that file
    Set oFld = oFSO.GetFolder(oFSO.GetParentFolderName(File))
End If

' Go through each file in that folder
For Each oFile In oFld.Files

    ' Only open the CSV files
    If oFile.Type = "Microsoft Excel Comma Separated Values File" Then
        ' Open it and set the first sheet (There is only one anyway)
        Set wbCSV = Workbooks.Open(oFile)
        Set CSV = wbCSV.Sheets(1)
        ' ============================
        ' Do what you want to do Here

        ' THIS IS A PLACEHOLDER
        ' Example to copy value of H8 in the CSV file to A2 the destination worksheet so you can see how to point to the correct cells in both files
        MyWs.cells(1,2).value = wCSV.cells(8,8).value

        ' End of what you want to do
        ' ============================

        ' Close the CSV file without savings changes before going through the next one
        wbCSV.Close False

    End If

Next oFile

End Sub

我希望这有帮助!祝你学习更多 VBA 好运!

最好的,朱利安

于 2013-07-02T16:23:44.983 回答