VBA Run-time error 1004
I'm programmng Excel Macro by VBA. Some problems happened.
There are 3 Excel files. One is old version excel file(extended format : xls) and the others are xlsx format.
I want to get the last row position of each file. My code is below.
Sub macro()
Dim testWorkBook1 As Workbook, testWorkBook2 As Workbook, testWorkBook3 As Workbook
Dim testSheet1 As Worksheet, testSheet2 As Worksheet, testSheet3 As Worksheet
Dim count1 As Integer, count2 As Integer, count3 As Integer
Set testWorkBook1 = Workbooks.Open("D:\test folder\test1.xls") ' line a --> xls format
Set testWorkBook2 = Workbooks.Open("D:\test folder\test2.xlsx")
Set testWorkBook3 = Workbooks.Open("D:\test folder\test3.xlsx") 'line b
Set testSheet1 = testWorkBook1.Sheets(1)
Set testSheet2 = testWorkBook2.Sheets(1)
Set testSheet3 = testWorkBook3.Sheets(1)
count3 = testSheet3.Cells(Rows.count, 1).End(xlUp).Row
count2 = testSheet2.Cells(Rows.count, 1).End(xlUp).Row
count1 = testSheet1.Cells(Rows.count, 1).End(xlUp).Row 'the point where runtime error 1004 happened
End Sub
When running code, run-time error 1004 happened. I tried serveral other cases. and i knew 2 things so far.
- if test1 file is "xlsx" version , the program runs successfully.
- if the 'line a' placed 'line b' below, the program also runs successfully. for example,
Set testWorkBook2 = Workbooks.Open("D:\test folder\test2.xlsx")
Set testWorkBook3 = Workbooks.Open("D:\test folder\test3.xlsx") 'line b
Set testWorkBook1 = Workbooks.Open("D:\test folder\test1.xls") ' line a --> xls format
I would like to get not only the solution but also the reasons.
countX = testSheetX.Cells(testSheetX.Rows.count, 1).End(xlUp).Row
. Especially when working with different workbooks usingRows
,Cells
etc. can be tricky. – cr44shAs Long
instead ofInteger
. Excel has more rows thanInteger
can handle! I recommend to always use Long instead of Integer as there is no benefit in usingInteger
in VBA. Also make sure that you useWorksheets
and notSheets
. Sheets can be a Chart sheet too and a chart sheet has no.Rows
. So if yourSheets(1)
is a chart it will fail. UseWorksheets(1)
instead. – Pᴇʜ