我希望這是一個正確的地方來問這個問題,因爲我正處於瘋狂的邊緣。我很生疏,我有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是否將記錄保存在停止搜索的位置? –
你可以看看我在頂部使用的代碼嗎? –