excel - IF 来自多个工作表的函数数据粘贴到空白工作表 VBA
问题描述
抱歉,如果这是重复的,但我不知道如何正确表达。
我有一个包含 7 个工作表的工作簿,所有工作表的名称都不同。
我想编写一个 if 函数来搜索所有工作表,如果它符合该条件以粘贴到“名称”表中。我尝试了多种方法,但无法做到这一点。这是我将获得标准的地方。
Dim Client As String
Client = InputBox("Enter the Clients name")
如果我从一张表中提取数据,则此代码有效:
Dim pasteRowIndex As Long
pasteRowIndex = 2
Dim LR as Long
LR = Cells(Rows.Count, 1).End(xlUp).Row
For I = 2 To LR
If Cells(I, 1).Value = Client Then
'Now the code to grab the data and past into a new workbook
Rows(I).Select 'This just works on the active sheet, but I want this to iterate through
all the sheets and paste the range into sheet2 in this code
Selection.Copy
'Switch to the sheet where you want to paste it & paste
Sheets("Sheet2").Select 'However I will change this name
Rows(pasteRowIndex).Select
ActiveSheet.Paste
'Next time you find a match, it will be pasted in a new row
pasteRowIndex = pasteRowIndex + 1
'Switch back to your table & continue to search for your criteria
'Sheets("Sheet1").Select
End If
Next I
虽然上面的代码适用于单个工作表,但我希望宏遍历所有工作表,并且它们没有命名为 Sheet1-Sheet7。
此外,必须有一种更清洁的方法来执行此操作。
如果不清楚,请道歉,如果需要更清楚,请告诉我。
解决方案
您可以按照以下示例代码遍历工作簿中的所有工作表:
Dim Sht As Worksheet
For Each Sht In Worksheets
If Sht.Name <> "Sheet1" Or Sht.Name <> "Sheet7" Then
'Do your stuff here
'sample code to refer the row at specific sheet without activating it
Sht.Rows(I).Copy
Sheets("Sheet2").Cells(pasteRowIndex, 1).PasteSpecial xlPasteAll
End If
Next
建议避免使用 .Select 和 .Activate 方法。而是使用 Worksheet 变量来引用特定的工作表。
推荐阅读
- python - python pptx 如何根据 XL_CHART_TYPE.LINE 更改图表中的线条格式
- hsqldb - 阿帕奇方解石 | HSQLDB - 未找到表异常
- android - 按钮点击事件 Android studio 多个 XML 文件
- php - 如何从 mysqli 数据库执行 php 脚本
- php - php mysqli插入重复值
- javascript - 在 JS 应用程序中在运行时加载预编译的包
- javascript - 使用 Ajax 填充多选下拉列表
- vba - Excel Vba 文本框段落
- javascript - AngularJS - 下拉菜单的问题
- spring-cloud-sleuth - Spring sleuth 中的 WebClient 检测