0

我是 EXCEL 的新手(尤其是 VBA)。我尝试编写以下逻辑:

转到所有打开的书籍,如果某本书有名为“Test”的工作表,它应该从命名范围“Table”中获取数据,然后将其附加到书籍 ALLDATABOOK 中工作表 ALLDATA 中的 Table1。我试着写这个,有人可以帮助我吗?

这是我的代码:

Private Sub CommandButton1_Click()
   Dim book As Object
    Dim lst As ListObject
   Dim iList As Worksheet
   For Each book In Workbooks

   For Each iList In book.Sheets
        If iList.Name = "Test" Then

        book.Sheets(iList.Name).Activate
Range("Table").Select


        End If
    Next

   Next
End Sub
4

1 回答 1

1

试试这个(为 Excel 2007+ 编写,可能不适用于早期版本)

Private Sub CommandButton1_Click()
    Dim book As Workbook
    Dim lst As ListObject
    Dim iList As Worksheet
    Dim Rng As Range

    Dim wbAllDataBook As Workbook
    Dim shAllData As Worksheet

    ' Get reference to ALLDATA table
    Set wbAllDataBook = Workbooks("ALLDATABOOK.xlsm")  '<-- change to suit your file extension
    Set shAllData = wbAllDataBook.Worksheets("ALLDATA")
    Set lst = shAllData.ListObjects("Table1")

    For Each book In Workbooks
        ' Use error handler to avoid looping through all worksheets
        On Error Resume Next
        Set iList = book.Worksheets("Test")
        If Err.Number <> 0 Then
            ' sheet not present in book
            Err.Clear
            On Error GoTo 0
        Else
            ' If no error, iList references sheet "Test"
            On Error GoTo 0
            ' Get Reference to named range
            Set Rng = iList.[Table]
            ' Add data to row below existing data in table.  Table will auto extend
            If lst.DataBodyRange Is Nothing Then
                ' Table is empty
                lst.InsertRowRange.Resize(Rng.Rows.Count).Value = Rng.Value
            Else
                With lst.DataBodyRange
                    .Rows(.Rows.Count).Offset(1, 0).Resize(Rng.Rows.Count).Value = Rng.Value
                End With
            End If
        End If
    Next
End Sub

更新:

要与 Excel 2003 一起使用,请替换

If lst.DataBodyRange Is Nothing Then

If Not lst.InsertRowRange Is Nothing Then
于 2012-09-20T08:59:27.607 回答