在Excel中导入之前过滤CSV文件

我想导入一个看起来像这样的CSV文件(逗号是分隔符):

x,y 

这里, x代表用户ID, y代表我想要提取的值。

其次,我有一个Excel文件,其第一列中的用户标识相似但方式较less。 我想导入只包含在Excel文件中的用户的y值。

有谁知道这是怎么做到的吗?

你可以使用ADO。 大致:

 Dim cn As Object Dim rs As Object Dim strFile As String Dim strCon As String Dim strSQL As String Dim TextInput As String ''This is not the best way to refer to the workbook ''you want, but it is very convenient for notes ''It is probably best to use the name of the workbook. strFile = ActiveWorkbook.FullName ''Note that if HDR=No, F1,F2 etc are used for column names, ''if HDR=Yes, the names in the first row of the range ''can be used. '' ''This is the ACE connection string, you can get more ''here : http://www.connectionstrings.com/excel strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _ & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";" TextInput = "[Text;FMT=Delimited;HDR=Yes;IMEX=2;DATABASE=Z:\docs]" ''Late binding, so no reference is needed Set cn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") cn.Open strCon strSQL = "SELECT a.ID,a.Data " _ & "FROM " & TextInput & ".[TestIn.csv] a " _ & "INNER JOIN [Sheet1$] b ON a.ID=b.ID" _ rs.Open strSQL, cn, 3, 3 ''Pick a suitable empty worksheet for the results Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs ''Tidy up rs.Close Set rs = Nothing cn.Close Set cn = Nothing 

假设你的数据中有唯一的用户ID(包括Excel文件和CSV),我只需要在单独的选项卡上将CSV导入到Excel中,然后用你需要的ID子集做一个简单的VLOOKUP()文件)来获得这些特定的y值。

注意 :我知道引入CSV 之前,这并不是真的过滤任何东西,但它可以很容易地完成工作(取出y值)。 如果你正在寻求自动化这个任务,那么希望有人有一个更具编程的回答:)

我会做这样的事情,你检查自己的每个用户ID。 改变它使它为你工作。 它应该会很快。

注意:我有一个对Microsoft Scripting Runtime的引用,它启用了DictionaryFileSystemObjectFileTextStream对象。

 Sub test() Dim i As Long Dim dicItems As Dictionary Dim fso As FileSystemObject Dim oFile As File Dim saItems() As String, saReturn() As String Dim oStream As TextStream Dim vUserID As Variant 'Get stream of file Set fso = New FileSystemObject Set oFile = fso.OpenTextFile("YourFile.csv") Set oStream = oFile.OpenAsTextStream(ForReading) Set dicItems = New Dictionary 'loop through items that you want extracted and put in dictionary vUserID = Range("A1", Range("A" & Rows.Count).End(xlUp)).Value2 ReDim saReturn(1 To UBound(vUserID)) For i = 1 To UBound(vUserID) dicItems.Add vUserID(i, 1), i Next i 'Loop through stream lines Do While Not oStream.AtEndOfStream saItems = Split(oStream.ReadLine, ",") If dicItems.Exists(saItems(0)) Then saReturn(dicItems(saItems(0))) = saItems(1) End If Loop 'Return information to your spreadsheet Range("B1", Range("B" & UBound(saReturn))) = Application.Transpose(saReturn) End Sub