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

时间:2017-09-07 11:15:56

标签: excel vba excel-vba

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

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

为此,我有以下代码。我想知道,如果有可能,只提一下工作簿名称而不提工作表名称?每次保存新的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

1 个答案:

答案 0 :(得分:1)

Mikz,您使用Worksheets的属性Workbook。此属性包含一个普通的VBA Excel集合(工作表)。您可以通过它的位置(整数)或其(字符串)来访问任何集合的成员。您在代码中使用 key ,因为您使用字符串值。如果您的工作簿中只有一个工作表,那么您肯定应该使用位置值,即1 - OriginWB.Worksheets(1).并且无论工作表的名称如何都可以使用。

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

遍历该集合

BTW - 我建议您使用WITH运算符OriginWB.Worksheets("1")恕我直言,它将帮助您制作更短,更易读的代码。您可以使用嵌套的WITH运算符。