VBA如何改进此代码并使之更高效?

时间:2019-05-20 00:52:22

标签: excel vba

我的vba excel有此代码。我一次又一次重复相同的代码,将我的值从sheet2添加到sheet1。有帮助吗?

    For j = 1 To Sheet1LastRow
    For i = 1 To Sheet2LastRow
        If Worksheets("sheet1").Cells(j, 7).Value = Worksheets("sheet2 ").Cells(i, 1).Value Then
            Worksheets("sheet1").Cells(j , 11).Value = Worksheets("sheet2").Cells(i ,1 ).Value
            Worksheets("sheet1").Cells(j, 12).Value = Worksheets("sheet2").Cells(i, 2).Value
            Worksheets("sheet1").Cells(j, 13).Value = Worksheets("sheet2").Cells(i, 3).Value
            Worksheets("sheet1").Cells(j, 14).Value = Worksheets("sheet2").Cells(i, 4).Value


        Else
        End If
Next i
Next j

1 个答案:

答案 0 :(得分:1)

可以一次操作复制连续范围:

Dim sht1 As Worksheet, sht2 As Worksheet  

Set sht1  = Worksheets("Sheet1")
Set sht2  = Worksheets("Sheet2")

For j = 1 To Sheet1LastRow
    For i = 1 To Sheet2LastRow
        If sht1.Cells(j, 7).Value = sht2.Cells(i, 1).Value Then
                sht1.Cells(j, 11).Resize(1, 4).Value = _
                              sht2.Cells(i, 1).Resize(1, 4).Value
        End If
    Next i
Next j