在你VBA IDE從工具菜單和selecte引用。選擇「Microstoft ActiveX數據對象2.8庫」。
這裏假設您的第一個列表位於表1中,第二個列表位於表2中,時間位於列A中,值位於列B中。它將數據寫出到工作表你想將有助於輸出更爲3.
Private Sub LineUpLists()
Dim ws1 As Excel.Worksheet
Dim ws2 As Excel.Worksheet
Dim ws3 As Excel.Worksheet
Set ws1 = ActiveWorkbook.Sheets("Sheet1")
Set ws2 = ActiveWorkbook.Sheets("Sheet2")
Set ws3 = ActiveWorkbook.Sheets("Sheet3")
Dim rs As New ADODB.Recordset
Dim lRow As Long
'Add fields to your recordset for storing data. You can store sums here.
With rs
.Fields.Append "Row", adInteger
.Fields.Append "Time", adDouble
.Fields.Append "Value1", adSingle
.Fields.Append "Value2", adSingle
.Open
End With
'Read the first list from sheet one.
lRow = 1
ws1.Activate
'Loop through the first list and record what is in the columns
Do While lRow <= ws1.UsedRange.Rows.count
If ws1.Range("A" & lRow).Value <> "" Then
rs.AddNew
rs.Fields("Row").Value = lRow
rs.Fields("Time").Value = Trim(str(ws1.Range("A" & lRow).Value))
rs.Fields("Value1").Value = ws1.Range("B" & lRow).Value
rs.Update
End If
lRow = lRow + 1
ws1.Range("A" & lRow).Activate
Loop
'Read the second list from sheet 2
lRow = 1
ws2.Activate
'Loop through the second list and record what is in the columns
Do While lRow <= ws2.UsedRange.Rows.count
If ws2.Range("A" & lRow).Value <> "" Then
'Check if we already recorded this time in the first list
rs.Filter = ""
rs.Filter = "Time=" & Trim(str(ws2.Range("A" & lRow).Value))
If rs.RecordCount = 1 Then
'If we already have this time, record the second list value
rs.Fields("Row").Value = lRow
rs.Fields("Time").Value = Trim(str(ws2.Range("A" & lRow).Value))
rs.Fields("Value2").Value = ws2.Range("B" & lRow).Value
rs.Update
Else
'If we didn't see this time on the first list, create a new record for it.
rs.AddNew
rs.Fields("Row").Value = lRow
rs.Fields("Time").Value = ws2.Range("A" & lRow).Value
rs.Fields("Value2").Value = ws2.Range("B" & lRow).Value
rs.Update
End If
End If
lRow = lRow + 1
ws2.Range("A" & lRow).Activate
Loop
rs.Filter = ""
rs.Sort = "Time"
'Switch to sheet 3
ws3.Activate
ws3.Range("B1").Value = "Time"
ws3.Range("B1").Value = "List1"
ws3.Range("C1").Value = "List2"
lRow = 2
'Here we loop through the data we collected and write it out.
Do While rs.EOF = False
ws3.Range("A" & lRow).Value = Format(rs.Fields("Time").Value, "hh:mm:ss")
ws3.Range("B" & lRow).Value = rs.Fields("Value1").Value
ws3.Range("C" & lRow).Value = rs.Fields("Value2").Value
lRow = lRow + 1
rs.MoveNext
Loop
End Sub
詳細一點 - 例如,你想要的東西像SQL的結果'OUTER JOIN'(行排列在那裏匹配,但在空白不匹配行)? – aucuparia
是1,2,3行號或在列的實際值? – MatthewD
如果我理解正確的話它做什麼OUTER JOIN是不是我要找的。至於第一colomn,是那些排數字,MatthewD的代碼輸出我的預期。 –