2010-06-14 133 views
1

我想加入2个不同的工作表中的2个独立的列,使一个更长的列,然后我可以使用Vlookup。Excel VBA/SQL联盟

Sheet 1中 A,B,C,d,E,F,G

Sheet 2中 A,B,C,d,E,F,G

欲加入(联盟)色谱柱B从sheet1和C从sheet2一起找到新列表的Distinct值。我一直在为此工作数周。

谢谢

回答

5

您可以在Excel中使用ADO。

Dim cn As Object 
Dim rs As Object 
Dim strFile As String 
Dim strCon As String 
Dim strSQL As String 
Dim s As String 
Dim i As Integer, j As Integer 

''This is not the best way to refer to the workbook 
''you want, but it is very conveient 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 Jet 4 connection string, you can get more 
''here : http://www.connectionstrings.com/excel 

strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _ 
    & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";" 

''Late binding, so no reference is needed 

Set cn = CreateObject("ADODB.Connection") 
Set rs = CreateObject("ADODB.Recordset") 


cn.Open strCon 

''A sample query 
strSQL = "SELECT Distinct A, B C FROM (" _ 
     & "SELECT A, B, C " _ 
     & "FROM [Sheet1$] " _ 
     & "UNION ALL " _ 
     & "SELECT A, B, C " _ 
     & "FROM [Sheet2$]) As J " 


''Open the recordset for more processing 
''Cursor Type: 3, adOpenStatic 
''Lock Type: 3, adLockOptimistic 
''Not everything can be done with every cirsor type and 
''lock type. See http://www.w3schools.com/ado/met_rs_open.asp 

rs.Open strSQL, cn, 3, 3 

''Write out the data to an empty sheet (no headers) 
Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rss 
+0

完美的作品。还有一件事。在Sheet1上,前两行是标题信息,而Sheet2前四个是标题信息。有关如何排除这些的任何建议? – Edge 2010-06-15 14:53:17

+0

HDR =是在连接字符串中将允许一个标题行,这可能不适合,所以也许更改为HDR =否,并向表单中添加一个范围,例如“FROM [Sheet1 $ A3:C102]”。当HDR = No时,您必须使用F1,F2 ... Fn – Fionnuala 2010-06-15 15:39:04

+0

PERFECT参考列。非常感谢你 – Edge 2010-06-15 15:51:12