excel - 根据 2 个标准输入将行从一个 Excel 工作表复制到另一个工作表
问题描述
我有一个 Excel 表,其中第一张表包含所有主数据,大约 500 行并跨越 R 列,该表称为整体表。O 列包含一个月,P 列包含一年。
我有另一张表,我希望在其中复制数据,这称为“预测月”。在 B1 的顶部,选择了我要复制的月份,在 D1 中,选择了年份。我希望按钮读取这两个单元格并基于此从“整体工作表”中复制数据。
我已经编写了如下所示的代码,但由于某种原因,数据在添加下一个(也是 10 次)之前输入了 10 次“预测月份”。我应该在这张表中只有 3 条数据,但每个有 30、10 条数据。
此外,每张纸上的前 3 行都有标题,因此数据应该从第 4 行开始写入(确实如此)
请问有人可以帮忙吗??
Private Sub CommandButton1_Click()
Dim month As String
Dim year As String
Dim c As Range
Dim d As Range
Dim k As Integer
Dim source As Worksheet
Dim targetforecastmonth As Worksheet
'change worksheet designations as needed
Set source = ActiveWorkbook.Worksheets("Overall Sheet")
Set targetforecastmonth = ActiveWorkbook.Worksheets("Forecast Month")
targetforecastmonth.Range("A4:Z1000").Clear
month = ActiveWorkbook.Worksheets("Forecast Month").Range("B1")
year = ActiveWorkbook.Worksheets("Forecast Month").Range("D1")
k = 4
For Each c In source.Range("O4:O1000")
For Each d In source.Range("P4:P1000")
If c = month And d = year Then
source.Rows(c.Row).Copy targetforecastmonth.Rows(k)
k = k + 1
End If
Next d
Next c
End Sub
解决方案
似乎有错误的逻辑。我想你需要 Expl.: O8, P8 匹配 B1, D1 所以你只需要一个循环:
For Each c In source.Range("O4:O1000")
d = source.Range("P" & k)
If c = month And d = year Then
source.Rows(c.Row).Copy targetforecastmonth.Rows(k)
End If
k = k + 1
Next c
推荐阅读
- android - 带有动态查询参数的 Android 浏览器意图链接
- r - 使用 R 连接到 bigquery 中的视图
- macos - 颤振'颤振干净'的詹金斯显示'不允许操作'
- javascript - 如何在角度用逗号替换换行符
- c# - 节点js中的Rfc2898DeriveBytes等价物
- sql - 连接速度是否取决于表中的记录总数?
- c# - 我有一个将数据保存到数据库的 post 方法,我需要返回保存记录的 id 并将另一个方法作为 Foreigh Key 传递
- visual-studio-code - 使用键绑定调用 VSCode 命令时未检测到所选文件
- java - 如何为 java.util.logging.FileHandler 使用 try-with-resources?
- python-3.x - 如何更新 tkinter 标签