[英]How to use VLOOKUP and get details from other sheet using VBA
我的工作簿中有以下表格
test,input,model,cm,mm,output
我想從輸入表中獲得輸入。
輸入
test mail god house dear moon son brother loosee man boy girl test
dd d d sd dfd 123 dfd ad d df sd d d
model
pop mark
123 jklm
CM
house dear mark
sd dfd love
MM
moon son
123 dfd
我正在嘗試編寫以下代碼以獲取所有細節並獲得輸出。 但是我失敗了請指導我解決它。
Option Explicit
Sub CopyRows()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim i As Integer, k As Integer
Dim ws1LR As Long, ws2LR As Long
Set ws1 = Sheets("input")
Set ws2 = Sheets("output")
ws1LR = ws1.Range("A" & Rows.Count).End(xlUp).Row + 1
ws2LR = ws2.Range("A" & Rows.Count).End(xlUp).Row + 1
i = 2
k = ws2LR
Do Until i = ws1LR
With ws1
.Range(.Cells(i, 1), .Cells(i, 18)).Copy
End With
With ws2
.Cells(k, 1).PasteSpecial
.Cells(k, 1).Offset(1, 0).PasteSpecial
End With
k = k + 2
i = i + 1
Loop
End Sub
我認為實現目標的最簡單方法是:
Sub prueba()
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1
Dim point2 As String
Dim point3 As String
Dim query As String
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")
objConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\Daniel\Desktop\prueba.xlsx;" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
query = "Select cm.dear FROM [input$] as i inner join [cm$] as cm on i.house = cm.house where test is not null"
objRecordset.Open query, _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
'since query returns one row so:
point2 = objRecordset.Fields.Item("dear") '<---- returns "dfd"
objRecordset.Close
query = "Select mm.moon FROM [input$] as i inner join [mm$] as mm on i.house = mm.house where test is not null"
'following line cant return any value because there is not any house field on mm table
objRecordset.Open query, _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
point3 = objRecordset.Fields.Item("moon")
End Sub
您應該知道的有關此代碼的所有內容,是如何編寫正確的查詢。
注意查詢變量,它就像一個sql查詢,你可以連接幾個表並查找兩個字段(列)中這兩個值相等的值。 那是因為你無法運行第二個查詢,因為在mm表中沒有一個名為house的字段(相應於你的例子)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.