I'm trying to use the following code to copy some values from an opened csv file to the sheet I'm working on. It works sometimes but will occasionally go through awb.Sheets("Target").Range("A2:C" & lrow).Value = wb.Sheets("csvSheetName").Range("A2:C" & lrow).Value
without actually copying any values.
I've stepped through the code and there doesn't see to be any problem. I've tried debugging it: awb.Sheets("Target").Range("A2:C" & lrow).Select
and wb.Sheets("csvSheetName").Range("A2:C" & lrow).Select
both grab the correct ranges, debug.print wb.Sheets("csvSheetName").Range("A1").Value
outputs what it should. lrow
has value.
On Error Resume Next
Sheets("Target").ShowAllData
On Error GoTo -1
Sheet5.Range("A2:A7000").Cells.ClearContents
Sheets("Target").Range("A2:C7000").Cells.ClearContents
Dim wb As Workbook
Dim awb As Workbook
Dim myfilename As String
Set awb = Workbooks("TargetBook")
myfilename = "www.csvwebsite.com/download.do?query=string"
Set wb = Workbooks.Open(myfilename)
`Application.Wait (Now + TimeValue("0:00:02"))
Application.Wait (Now + TimeValue("0:00:10"))
lrow = wb.Sheets("csvSheetName").Cells(Sheets("csvSheetName").Rows.Count, "A").End(xlUp).Row
awb.Sheets("Target").Range("A2:C" & lrow).Value = wb.Sheets("csvSheetName").Range("A2:C" & lrow).Value
Application.Wait (Now + TimeValue("0:00:02"))
wb.Close
The destination range is still blank after that line passes with no error. Usually I can rerun the sub and it will work but this is for a project that's effectively a server backend and is running 24/7. When I tried to debug it yesterday, I wasn't able to get it to work at all. The whole range is usually about 3000 cells total so I don't think it's overloading the memory.
I'm open for other ways to do this but it can't copy-paste as the computer is usually locked when doing this, I found that using the clipboard is finicky in that case. I'm also curious as to why this would only work sometimes... I hate it when something works some of the time.
EDIT: Set awb = ActiveWorkbook
to Set awb = Workbooks("TargetBook")
I think that was the reason it didn't work yesterday when I manually stepped through it. The issue was still present after this change, but when I see it, stepping through fixes it.
EDIT2: Increased waiting time after opening workbook to 10 seconds for now.
EDIT3: No issues with either the increased wait time or the change in the accepted answer. Likely something to do with VBA skipping over the object if it wasn't completely loaded.