问题
I have done a thorough search but cannot find an answer for my specific issue, using Microsoft Excel 2003.
I need to copy Column R descriptions (alphanumerical) from one xls spreadsheet (let's call it ssA) to columns L & M in another spreadsheet (ssB), by svc_itm_cde (service item code). There are about 300 svc_itm_cdes.
Three complications:
- The svc_itm_cde column in ssA is not in the same order as the one in ssB.
- Some of the rows of L & M in the ssB already contain descriptions and must be skipped.
- Some of the svc_item_cdes in ssB do not appear in ssA, and vice versa.
A friend helped me export to cvs and begin a Python script, but that was too longwinded. Is there any way to do this with vba code (preferably)?
Many thanks.
回答1:
This might be an over-complicated way of doing this for 300 records but it's a useful technique for larger datasets...
If you just need to get all of the data together in one place so you can work out which descriptions to keep and which to lose then you could use ADO and join the two data sets together.
Start by going to the Visual Basic Editor (press Alt+F11). Once there use Tools > References to add a reference to "Microsoft ActiveX Data Objects 2.8 Library"
Now Insert > Module and paste in this code:
Option Explicit
Sub master_list()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
' This is the connection string for .xlsx files (Excel 2007 and later)
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 12.0 Xml;"
.Open
End With
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM [ssA$] LEFT JOIN [ssB$] ON [ssA$].[svc_itm_cde] = " & _
"[ssB$].[svc_itm_cde] UNION ALL SELECT * FROM [ssA$] RIGHT JOIN [ssB$] ON " & _
"[ssA$].[svc_itm_cde] = [ssB$].[svc_itm_cde] " & _
"WHERE [ssA$].[svc_itm_cde] IS NULL;", cn
Dim i As Integer
Dim fld As ADODB.Field
i = 0
' Sheet3 should be a blank sheet that we can output the results to
With Worksheets("Sheet3")
For Each fld In rs.Fields
i = i + 1
.Cells(1, i).Value = fld.Name
Next fld
.Cells(2, 1).CopyFromRecordset rs
End With
rs.Close
cn.Close
End Sub
If you are using Excel 2003 or earlier then the connection string part should be:
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 8.0;"
.Open
End With
来源:https://stackoverflow.com/questions/14328896/microsoft-excel-2003-copying-out-of-order-descriptions