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

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

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

对于任何值为“TotalLMP”(样本:单元格H8 =“TotalLMP”)的单元格,请检查H行至CA列中的IF行8

那么将第8行中具有该值=“TotalLMP”的任何列的第7行和第19行的值复制到两个新列(样本:SINCE H8 =“TotalLMP”,COPY H7 =“100”作为列A,副本H19 =“26.437”AS COLUMN B)

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

完成每个csv文件的循环后closures并转到下一个

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

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

1 .. 100 …. 26.437 …. 20100101

2 .. 200 …. 26.585 …. 20100101

现在让我来帮助你,因为这对初学者来说很难。 我相信你会弄清楚如何在第8行testing一个值。如果没有,你总是可以要求更多的帮助!

为此,您将不得不使用Microsoft脚本运行时。

我build议把你想要打开的所有csv文件放在同一个目录下,只有那些才能避免潜在的问题。

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

将工作簿保存为与CSV(或其他位置)相同的目录中已启用macros的工作簿(.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!

最好的Julien