我希望这是一个正确的地方来问这个问题,因为我正处于疯狂的边缘。我很生疏,我有VBA(只适用于C++,JAVA)从外部工作簿复制数据基于标题不是为了另一个工作簿
问题零经验: 我试图将数据从一个工作簿复制到另一个。
可以说我有一个工作簿(称为数据)与几个充满数据的工作表。每一列数据都有一个唯一的标题(同一行上的所有标题)。
另一方面,我有另一个工作簿(称为报告)与一个工作表,只包含数据的标题(在一行)。它们与DATA工作簿中的顺序不同。例如,我在REPORT工作表中可以在DATA工作簿的不同工作表中找到3个标题。
我需要遍历DATA工作簿中的所有工作表,并在找到相同标题时将整列粘贴到REPORT工作表中。
此图片可能有助于理解。Explanation
非常感谢ALOT提前给予的帮助。我已经搜索了很多代码,但发现类似的东西,但没有设法了解任何。
首先尝试这样做,但得到运行时错误“1004”的错误。 有什么帮助吗?
Dim MyFile As String
Dim ws As Worksheet
''Workbook that contains one worksheet with all the headings ONLY NO DATA
Dim TargetWS As Worksheet
Set TargetWS = ActiveSheet
Dim TargetHeader As Range
''Location of Headers I want to search for in source file
Set TargetHeader = TargetWS.Range("A1:G")
''Source workbook that contains multiple sheets with data and headings _
not in same order as target file
Dim SourceWB As Workbook
Set SourceWB = Workbooks("Source.xlsx")
Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
Dim SourceCell As Range
''Stores the col of the found value and the last row of data in that col
Dim RealLastRow As Long
Dim SourceCol As Integer
''Looping through all worksheets in source file, looking for the heading I want _
then copying that whole column to the target file I have
For Each ws In SourceWB.Sheets
ws.Activate
For Each Cell In TargetHeader
If Cell.Value <> "" Then
Set SourceCell = Rows(SourceHeaderRow).Find _
(Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not SourceCell Is Nothing Then
SourceCol = SourceCell.Column
RealLastRow = Columns(SourceCol).Find("*", LookIn:=xlValues, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If RealLastRow > SourceHeaderRow Then
Range(Cells(SourceHeaderRow + 1, SourceCol), Cells(RealLastRow, _
SourceCol)).Copy
TargetWS.Cells(2, Cell.Column).PasteSpecial xlPasteValues
End If
End If
End If
Next
Next
谢谢你的时间,一个小问题。找到数据工作表中的匹配后,我正在查看..如何选择此列并复制它? vba是否将记录保存在停止搜索的位置? –
你可以看看我在顶部使用的代码吗? –