从指定目录中的excel文件中提取某些单元格

时间:2013-07-02 15:55:59

标签: excel vba excel-vba

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

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

检查列H到CA中的第8行,以查找值为“TotalLMP”的任何单元格(示例:单元格H8 =“TotalLMP”)

然后将第8行中具有该值=“TotalLMP”的任何列的第7行和第19行中的值复制到两个新列中(示例:SINCE H8 =“TotalLMP”,COPY H7 =“100”AS COLUMN A,COPY H19 =“26.437”AS栏B)

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

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

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

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

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

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

1 个答案:

答案 0 :(得分:3)

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

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

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

打开一个新工作簿并转到VBE(ALT + F11)。创建一个新模块。单击此新模块,然后转到工具>参考及GT; Microsoft Scripting Runtime。这将让它知道它必须使用该模块及其对象。

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

然后开始编码:

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!

最佳, 于连