[英]Pulling data from another workbook using VBA in excel
I have a range of unique project IDs in 2 workbooks. 我在2个工作簿中有一系列唯一的项目ID。 One of the workbooks doesn't contain the details of the projects, while the other workbook contains all of the project details.
其中一个工作簿不包含项目的详细信息,而另一个工作簿则包含所有项目的详细信息。
I want to pull out the information from one workbook according to the unique project ID found in the other workbook. 我想根据另一工作簿中找到的唯一项目ID从一个工作簿中提取信息。 I have tried coding this, but it only works for extracting the data from the external workbook for the one with the project ID.
我已经尝试对此进行编码,但是它仅适用于从外部工作簿中提取具有项目ID的数据。 I need it to work to extract the data for a range of project IDs given in a column.
我需要它来提取列中给定的一系列项目ID的数据。
This is the code I currently have: 这是我目前拥有的代码:
Sub AAA()
If Workbooks("Source.xlsm").Sheets("Sheet2").Range("A2").Value = Workbooks("Target.xlsm").Sheets("Sheet1").Range("A2").Value Then
Workbooks("Source.xlsm").Sheets("Sheet2").Range("B2").Value = Workbooks("Target.xlsm").Sheets("Sheet1").Range("C2").Value
End If
End Sub
This code only works for a particular cell, but I would need to extract a range of data from a range of project IDs located in the external workbook. 这段代码仅适用于特定的单元格,但是我需要从外部工作簿中的一系列项目ID中提取一系列数据。 What can I do to get this to work?
我该怎么做才能使它正常工作?
As per your question you need to add one more loop try this 根据您的问题,您需要再添加一个循环,试试这个
Sub copydata()
Dim i As Long, j As Long
Dim targetlastrow As Long, sourcelstrow As Long
Dim Sourcelastcol As Long
Dim source As Worksheet
Dim target As Worksheet
Set source = Workbooks("Source.xlsm").Sheets("Sheet2")
Set target = Workbooks("Target.xlsm").Sheets("Sheet1")
targetlastrow = target.Range("A" & target.Rows.Count).End(xlUp).Row
sourcelstrow = source.Range("A" & source.Rows.Count).End(xlUp).Row
Sourcelastcol = source.Cells(2, source.Columns.Count).End(xlToLeft).Column
For i = 2 To targetlastrow
For j = 2 To sourcelstrow
If target.Range("A" & i).Value = source.Range("A" & j) Then
source.Activate
source.Range("B" & j).Select
Range(ActiveCell, ActiveCell.Offset(0, Sourcelastcol)).Copy
target.Range("B" & i).PasteSpecial
End If
Next j
Next i
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.