我有一个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
答案 0 :(得分:1)
似乎有错误的逻辑。 我想你需要解释: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
答案 1 :(得分:0)
尝试一下,希望对您有所帮助。
Private Sub CommandButton1_Click()
Dim month As String
Dim year As String
Dim c 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")
If c = month And source.Cells(c.Row, 16).Value = year Then
source.Rows(c.Row).Copy targetforecastmonth.Rows(k)
k = k + 1
End If
Next c
End Sub
答案 2 :(得分:0)
您有一个嵌套的For Each
循环,这意味着您先进入单元格"O4"
,然后遍历单元格"P4:P1000"
,然后再进入单元格"O5"
并遍历单元格{{1再次}},依此类推...例如,如果"P4:P1000"
的像元值满足"O4"
标准,则每次循环通过列P时都找到满足month
像元的像元,行号year
将被复制并粘贴。
尝试以下方法:
4