VBA vlookup,cut&糊

时间:2016-01-31 11:43:41

标签: vba excel-vba excel

我开始认为我离这个代码还有一英里的距离。我想在“r15”中找到值并在查找表中找到匹配项。然后,在该行和右侧的2列中,我想粘贴e15中的值。这就是我所拥有的:

Sub CopyX()
    MsgBox "FlightPlan for Profits PRO never actually DELETES an employee, It just marks an employee as inactive.  If the Employee were actually deleted from the database, archival records would not include a deleted employee (of course) and would therefore become inaccurate", vbInformation, "FlightPlan for Profits PRO"
    ActiveSheet.Range("e15").Select
    Selection.Copy
    vlookupVBA = Application.WorksheetFunction.vlookup(Range("r15"), Range("c24:c274"), 1, False)
        Range.Offset(0, 2).Select
    ActiveCell.PasteSpecial Paste:=xlPasteValues
End Sub

2 个答案:

答案 0 :(得分:1)

您错误地使用了VLOOKUP function。事实上,MATCH function将返回您似乎正在寻找的行号。

Sub CopyX()

    MsgBox "FlightPlan for Profits PRO never actually DELETES an employee." & Chr(10) & _
           "It just marks an employee as inactive. " & _
           "If the Employee were actually deleted from the database, archival records " & _
           "would not include a deleted employee (of course) and would therefore become inaccurate", _
           vbInformation, "FlightPlan for Profits PRO"

    With Worksheets("Sheet1")
        'first check if anything is there
        If CBool(Application.CountIf(.Range("c24:c274"), .Range("r15").Value)) Then
            'there is a row number to find; get it and set the value
            .Cells(Application.Match(.Range("r15").Value, .Range("c24:c274"), 0) + 23, "E") = _
                .Range("e15").Value
        End If
    End With

End Sub

当MATCH返回 C24:C274中的位置时,会添加23,并为Range.Cells property提供正确的 row_number 参数,以便从E15接收值

我添加了一个换行符并将您的msgbox文本分成几行,以便在没有右滚动的情况下保持可见。

答案 1 :(得分:0)

查找也适用于此。

Sub Button1_Click()
    Dim msg As String
    Dim lstRw As Long, rng As Range, c As Range

    lstRw = Cells(Rows.Count, "C").End(xlUp).Row
    Set rng = Range("C24:C" & lstRw)

    Set c = rng.Find(what:=Range("R15").Value, lookat:=xlWhole)

    msg = "FlightPlan for Profits PRO never actually DELETES an employee, " & vbNewLine
    msg = msg & "It just marks an employee as inactive. " & vbNewLine
    msg = msg & "If the Employee were actually deleted from the database, " & vbNewLine
    msg = msg & "archival records would not include a deleted employee (of course) " & vbNewLine
    msg = msg & " and would therefore become inaccurate"
    MsgBox msg, vbInformation, "FlightPlan for Profits PRO"

    If Not c Is Nothing Then
        Cells(c.Row, c.Column + 2).Value = Range("E15").Value
    Else: MsgBox "Not Found"
        Exit Sub
    End If


End Sub