简体   繁体   中英

VBA Macro to copy/paste cell value from sheet 1 to 2 based on date

I have anchored a date and a value in Sheet 1 and want to look up that date in Sheet 2's column A, and paste the sheet 1 value in sheet 2's column E.

In sheet 1, I have today's name as REP_DATE, and the date I want to look for is yesterday's date, which is REP_DATE - 1 and I have had this formula in sheet1 E5, and the value is in F5.

here is the code I have from online and I have made some adjustments:

Sub CopyData()
Dim myDate As Date
Dim myValue As Variant
myDate = ThisWorkbook.Sheets("Sheet1").Range("E6").Value
myValue = ThisWorkbook.Sheets("Sheet1").Range("F6").Value


ThisWorkbook.Sheets("Sheet2").Range("A:A").Find(myDate).Offset(0, 4).Value = myValue

End Sub

However, I'm keep getting an error "Run-time error '91': Object variable or With block variable not set", debug is referring to this line of code ThisWorkbook.Sheets("Sheet2").Range("A:A").Find(myDate).Offset(0, 4).Value = myValue

It really confuses me and I'm wondering how to solve this issue.

Thanks.

You described that you have your date/value in row 5 (e5, f5) while in your code you're looking for date by row 6 (e6, f6).

Error shows because the date is not found.

There will be the same error in case your date is not exist in Sheet2.

You can update cell adresses in your code. Additinally, you can add some error handling to let user know why code is not working corectlly in case date is not found;

Option Explicit

Sub CopyData()
Dim myDate As Date
Dim myValue As Variant
myDate = ThisWorkbook.Sheets("Sheet1").Range("E5").Value
myValue = ThisWorkbook.Sheets("Sheet1").Range("F5").Value

On Error GoTo nodate
ThisWorkbook.Sheets("Sheet2").Range("A:A").Find(myDate).Offset(0, 4).Value = myValue
On Error GoTo 0

Exit Sub

nodate:
    MsgBox ("Date is not found")
End Sub

Thanks to @Salamander Krajza, I will share my most updated code here, need to change the date on sheet2 from formula to value so that find function can work its magic:

Sub CopyData()
Dim myDate As Date
Dim myValue As Variant
myDate = ThisWorkbook.Sheets("Sheet1").Range("E5").Value
myValue = ThisWorkbook.Sheets("Sheet1").Range("F5").Value


On Error GoTo nodate
ThisWorkbook.Sheets("Sheet2").Range("A:A").Find(what:=myDate, LookIn:=xlValues, lookat:=xlWhole).Offset(0, 4) = myValue
On Error GoTo 0

Exit Sub

nodate:
    MsgBox ("Date is not found")
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM