[英]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.