[英]VBA vlookup, cut & paste
我開始認為我與這段代碼相距甚遠。 我想在“ 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
您使用的VLOOKUP功能不正確。 實際上, MATCH函數會返回您正在尋找的行號。
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屬性提供了正確的row_number參數,以便從E15接收值。
我添加了一個換行符,並將您的msgbox文本分成幾行,以使其可見而無需向右滾動。
查找也將為此工作。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.