问题
I have following sheet available in my workbook
test,input,model,cm,mm,output
I would like to get input from input sheet.
- add the column before the test column which is "mark" and vlookup based on house(,) to sheet "CM" house to mark.
- I need to get "dear" detail from "CM" based house
- I need to get "son" detail from "MM" based house
- I need to add column between brother and son. Which has named as mark and vlook based on son and get from model sheet.
Input
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
I am trying to write the following code to get all details and get output. but I am getting failed pls guide me to solve it.
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
回答1:
I think the easiest way to achieve your goals is:
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
All you should to know about this code, is how to write the proper query.
Pay attention to query variable, it's like a sql query, you can join several tables and look for a value where these two values in two fields (columns) are equal. That's because you cant run the second query, because there is not a field called house in mm table (accordingly to your example).
来源:https://stackoverflow.com/questions/35617903/how-to-use-vlookup-and-get-details-from-other-sheet-using-vba