Excel 将所有书籍中的数据放到某个表中
我对EXCEL(特别是VBA)非常陌生。我试着写下这样的逻辑: 转到所有打开的书籍,如果某本书有名为“Test”的工作表,它应该从命名范围“Table”中获取数据,然后从book ALLDATABOOK中的sheet ALLDATA将其附加到Table1中。我试着写这个,有人能帮我吗 这是我的密码:Excel 将所有书籍中的数据放到某个表中,excel,excel-2003,vba,Excel,Excel 2003,Vba,我对EXCEL(特别是VBA)非常陌生。我试着写下这样的逻辑: 转到所有打开的书籍,如果某本书有名为“Test”的工作表,它应该从命名范围“Table”中获取数据,然后从book ALLDATABOOK中的sheet ALLDATA将其附加到Table1中。我试着写这个,有人能帮我吗 这是我的密码: Private Sub CommandButton1_Click() Dim book As Object Dim lst As ListObject Dim iList As
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
尝试此操作(为Excel 2007+编写,可能不适用于早期版本)
与
thaks,但我使用的是excel 2003,我会尝试将来请用versionok标记excel问题,我在代码中看到一些问题:它只从我的每个命名范围中取第一行,(如果我选中命名范围,则有多行)哦,好的。只需使用
Resize
调整目标范围的大小-请参阅更新请参阅我的下一个问题:这是问题的继续
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
If lst.DataBodyRange Is Nothing Then
If Not lst.InsertRowRange Is Nothing Then