简体   繁体   中英

Excel VBA: Copy & Paste - Cells are being copied but not pasted

I am brand new to VBA and am working on writing some code that copies data from a column in one workbook and pastes the data into another.

See my code below:

Set src = Workbooks.Open("C:\Users\RP\Desktop\CopyFrom.xlsm", True, True)

Dim startRow As Integer, endRow as Integer
With src.Sheets("Sheet1")
    startRow = .Range("B:B").Find(what:="*", after:=.Range("B1")).Row
    endRow = .Range("B:B").Find(what:="", after:=.Range("B1"), searchdirection:=xlPrevious).Row
End With

src.Worksheets("Sheet1").Range("B" & startRow & ":B" & endRow).Copy
Sheets("PasteHere").Range("B1").PasteSpecial xlPasteValues

I have startRow and startRow since the data is in Column B but does not start in cell B1 .

When I run the macro, I see that the data from the src file is copied (it has the dotted "ants" around it and I can paste it wherever I please). However, in my current workbook, there is no data pasted.

Can you help me figure this out? Thank you!

As was commented you don't need to copy and paste if you just need the values; in fact copy and paste is much slower than working with the values directly!

Set src = Workbooks.Open("C:\Users\RP\Desktop\CopyFrom.xlsm", True, True)
Set dest = Workbooks.Open("C:\Users\RP\Desktop\CopyTo.xlsm", True, True)

Dim startRow As Integer, endRow as Integer
With src.Sheets("Sheet1")
    startRow = .Range("B:B").Find(what:="*", after:=.Range("B1")).Row
    endRow = .Range("B:B").Find(what:="", after:=.Range("B1"),      searchdirection:=xlPrevious).Row
End With

dest.Worksheets("PasteHere").Range("B1").Value = _ 
    src.Worksheets("Sheet1").Range("B1").Value

You can learn more about the Range object here:

https://docs.microsoft.com/en-us/office/vba/api/excel.range(object)

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