复制两个匹配的其他列

时间:2014-02-19 06:32:25

标签: excel vba excel-vba

我有两个电子表格

main.xlsm

enter image description here

uat.xlsx

enter image description here

如果main.xlsm中的列A(1)与uat.xlsx中的列B(2)之间存在匹配,我还想将uat.xlsx中C(3)列中的值复制到N列(14)在main.xlsm中,以及在main.xlsm 中匹配行的main.xlsm 中的uat.xlsx到列Q(14)中的列D(4)中的值。

我已经在代码上取得了先机,但我想将上述内容添加到其中 - 我将如何进行此操作?

Sub UAT_Update()
Dim wshT As Worksheet
    Dim wbk As Workbook
    Dim wshS As Worksheet
    Dim r As Long
    Dim m As Long
    Dim cel As Range
    Application.ScreenUpdating = False
    Set wshT = ThisWorkbook.Worksheets("Master")
    On Error Resume Next

    ' Check whether uat.xlsx is already open
    Set wbk = Workbooks("uat.xlsx")
        On Error GoTo 0
        If wbk Is Nothing Then
        ' If not, open it
        Set wbk = Workbooks.Open("C:\Working\uat.xlsx")
    End If

    ' Set worksheet on uat.xlsx
    Set wshS = wbk.Worksheets("owssvr")
    m = wshT.Cells(wshT.Rows.Count, 1).End(xlUp).Row

    ' Optional - clear columns on main.xlsm
    ' wshT.Range(wshT.Cells(1, 13), wshT.Cells(m, 13)).ClearContents

    ' Loop though cells in column A on main.xlsm
    For r = 1 To m
        ' Can we find the value in column B of uat.xlsm?
        Set cel = wshS.Columns(2).Find(What:=wshT.Cells(r, 1).Value, _
            LookAt:=xlWhole, MatchCase:=False)

        If Not cel Is Nothing Then
            ' If so, enter "Yes" in column M - Comms Sent?
                wshT.Cells(r, 13).Value = "Yes"
            ' Enter "Yes" in column O - VDA Deployed?
                wshT.Cells(r, 15).Value = "Yes"
            ' Enter "5.6.200" in column P - Version
                wshT.Cells(r, 16).Value = "5.6.200"
        End If
    Next r

    ' Update column headers
    wshT.Cells(1, 13).Value = "Comms Sent?"
    wshT.Cells(1, 14).Value = "OTP"
    wshT.Cells(1, 15).Value = "VDA Deployed?"
    wshT.Cells(1, 16).Value = "VDA Version"
    wshT.Cells(1, 17).Value = "Migration Date"

    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

我希望上面的代码运行良好。

我认为你应该改变这一行 - > wshT.Cells(r, 15).Value = "Yes"wshT.Cells(r, 15).Value = cel.offset(0,1).value

更新:

If Not cel Is Nothing Then                
                wshT.Cells(r, 15).Value = cel.offset(0,1).value

End If