我想导入一个看起来像这样的CSV文件(逗号是分隔符):
x,y
此处, x 表示用户ID, y 表示我想要提取的值。
其次,我有一个Excel文件,其第一列中的用户ID相似但方式较少。我想只导入Excel文件中包含的那些用户的 y 值。
有谁知道怎么做?
答案 0 :(得分:1)
您可以使用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
答案 1 :(得分:0)
假设您的数据中包含唯一的用户ID(包括Excel文件和CSV),我只需将CSV放入Excel中的单独选项卡上,然后使用您的ID子集执行简单的VLOOKUP()
需要(在Excel文件中)获取那些特定的y值。
注意:我知道在引入CSV之前,这并没有真正过滤任何,但它可以很容易地完成工作(拉出y值)。如果您希望自动完成此任务,那么希望有人能够获得更多程序化的答案:)
答案 2 :(得分:0)
我会做这样的事情,你自己检查每个用户ID。改变它,使它适合你。它应该很快。
注意:我引用Microsoft Scripting Runtime
来启用Dictionary
,FileSystemObject
,File
和TextStream
个对象。
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