[英]Copy Data from Sheet to another based on drop-down value
I have several sheets in one workbook.我在一个工作簿中有几张纸。 I want to copy-paste the data (entire content) from different sheets to sheet 1 (let's say from B6) based on the drop-down value in 'A2' in Sheet 1. Drop-down consists of names of all the other sheets.我想根据工作表 1 中“A2”中的下拉值将数据(整个内容)从不同工作表复制粘贴到工作表 1(比如说 B6)。下拉列表包含所有其他工作表的名称. So, if I select Sheet 2 in drop-down, it should copy entire content from Sheet 2 to Sheet 1, starting from B6.所以,如果我 select Sheet 2 在下拉列表中,它应该将整个内容从 Sheet 2 复制到 Sheet 1,从 B6 开始。
Here is the macro, I created for it.这是我为它创建的宏。 But it's not working.但它不起作用。 Can you help me figure out what's wrong with my code?你能帮我弄清楚我的代码有什么问题吗?
Sub Button21_Click()
Dim wb As Workbook
Dim criteria As String
Application.ScreenUpdating = False
'Set values for your variables.
Set wb = ThisWorkbook
criteria = wb.Sheets("Sheet1").Range("A2")
Dim TT As ListObject
For i = 1 To Sheets.Count
With Sheets(i)
For Each TT In Sheets(i).ListObjects
If TT.Name = criteria Then TT.Range.Copy Sheets("Sheet1").Range("B6:Q22").PasteSpecial: Exit Sub
Next
End With
Next
Application.ScreenUpdating = True
End Sub
Here's code that does work.这是有效的代码。
Sub Button21_Click()
Dim Wb As Workbook
Dim Criteria As String
Dim i As Integer ' loop counter: Sheets
Dim Tbl As ListObject ' loop object
'Set values for your variables.
Set Wb = ThisWorkbook
Criteria = Wb.Sheets("Sheet1").Range("A2")
Application.ScreenUpdating = False
For i = 1 To Wb.Sheets.Count ' { "Shees(1)" is in the ActiveWorkbook
' { which may be different from Wb
For Each Tbl In Wb.Sheets(i).ListObjects
If Tbl.Name = Criteria Then
Tbl.Range.Copy
Wb.Worksheets("Sheet1").Range("B6").PasteSpecial
Exit Sub
End If
Next Tbl
Next i
Application.ScreenUpdating = True
End Sub
Set Wb = ThisWorkbook
if you use the default workbook (= ActiveWorkbook) thereafter?如果此后使用默认工作簿(= ActiveWorkbook),那么声明Set Wb = ThisWorkbook
有什么意义?PasteSpecial
needs its own line. PasteSpecial
需要自己的行。 The construct you used would deliver the argument for the Copy
object's Destination
property.您使用的构造将为Copy
对象的Destination
属性提供参数。 The latter is an address and can't include the PasteSpecial
method.后者是一个地址,不能包含PasteSpecial
方法。 Note that the ListObject
's Range comprises of the entire table.请注意, ListObject
的 Range 包含整个表格。 Use the DataBodyRange
to specify only data (without headers and totals).使用DataBodyRange
仅指定数据(没有标题和总计)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.