我有一个 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
关于excel - 根据 2 个标准输入将行从一个 Excel 工作表复制到另一个工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53371332/