DanM
DanM

Reputation: 195

run time error 9, trying to get the lastrow in a newly opened file

here is my code that is failing

Dim OpenFileName As String
Dim wb As Workbook, wb2 As Workbook
Dim lastrow
'Select and Open workbook
OpenFileName = Application.GetOpenFilename(",*.csv")
If OpenFileName = "False" Then Exit Sub
Set wb = Workbooks(OpenFileName)
Set wb2 = Workbooks("MasterLogFile.xlsm")

MsgBox OpenFileName
With wb
'lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
Range("A3:ME" & lastrow).Copy
.Sheets("Log Imports").Range("A7").Paste
End With

it fails on the set wb line, what am i doing wrong?

Upvotes: 0

Views: 207

Answers (1)

Vityata
Vityata

Reputation: 43585

Change the code to this one:

Set wb = Workbooks.Open(OpenFileName)

Then close it at the end like this:

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-close-method-excel

Upvotes: 1

Related Questions