从另一个工作簿中提取数据,而不提及表单名称

我有两个工作簿。 源工作簿和目标工作簿。

我想从我的源工作簿中提取所有数据,具体取决于我的目标工作簿的标题。

为此,我有下面的代码。 我想知道,如果可以的话,只要提到工作簿名称而不提及表单名称呢? 每次我保存一个新的excel文件时,该表保存为sheet1,sheet2。 由于工作表名称的这种变化,我得到一个下标错误。

任何人都可以帮忙,我怎么可以从工作表中提取数据,而不必提到工作表名称。 在大多数情况下,在我的工作簿中,我只有一张纸。

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 

Mikz,你使用Worksheets Workbook属性Worksheets 。 该属性包含一个普通的VBA Excel集合(工作表)。 您可以通过位置 (整数)或 (string)访问任何集合的成员。 由于使用了string值,所以可以在代码中使用 。 如果您的工作簿中只有一个工作表,那么您肯定应该使用位置值,即1 – OriginWB.Worksheets(1). 它将工作,不pipe名单的名单。

如果您有多个工作表,则可以使用遍历集合
FOR EACH aWorksheet IN OriginWB.Worksheets

顺便说一句 – 我会build议你使用WITH运算符OriginWB.Worksheets("1")恕我直言,它会帮助你做出更短,更易读的代码。 你可以使用嵌套的WITH运算符。