私は2つのワークブックを持っています。ソースブックと宛先ブック。シート名に言及せずに別のブックからデータを抽出する
宛先ブックのヘッダーに応じて、ソースブックからすべてのデータを抽出したいと考えています。
このため、私は以下のコードを持っています。可能であれば、シート名に言及せずにワークブック名を言いたいのですが、私は知りたいのですか?新しいExcelファイルを保存するたびに、シートはsheet1、sheet2として保存されます。このシート名の変更により添え字エラーが発生します。
いずれにせよ、シート名に言及せずにシートからデータを抽出する方法はありますか。ほとんどの場合、私のワークブックには1枚しかありません。
Sub Extract()
Dim DestinationWB As Workbook
Dim OriginWB As Workbook
Dim path1 As String
Dim FileWithPath As String
Dim Lastrow As Long, i As Long, LastCol As Long
Dim TheHeader As String
Dim cell As Range
Set DestinationWB = ThisWorkbook
' get the path of this workbook
path1 = DestinationWB.Path
FileWithPath = path1 & "\Downloads\Sourcg.xlsx"
Set OriginWB = Workbooks.Open(filename:=FileWithPath)
'get the count of last row and column
Lastrow = OriginWB.Worksheets("1").Cells(Rows.count, 1).End(xlUp).Row
LastCol = OriginWB.Worksheets("1").Cells(1, Columns.count).End(xlToLeft).Column
For i = 1 To LastCol
'get the name of the field (names are in row 1)
TheHeader = OriginWB.Worksheets("1").Cells(1, i).Value
With DestinationWB.Worksheets("S").Range("A4:L4")
'Find the name of the field (TheHeader) in the destination (in row 4)
Set cell = .Find(TheHeader, LookIn:=xlValues)
End With
If Not cell Is Nothing Then
OriginWB.Worksheets("1").Range(Cells(2, i), Cells(Lastrow, i)).Copy Destination:=DestinationWB.Worksheets("S_APQP").Cells(5, cell.Column)
Else
'handle the error
End If
Next i
OriginWB.Close SaveChanges:=False
End Sub
最初のワークシートは、インデックス '.Worksheets(1)'で参照できます。 – omegastripes