Some user
Some user

Reputation: 49

issues with Run time error 9 on vba code

I need help debugging a weird bug i found on one of my workbooks. I wrote some vba code for an excel file and it somehow calling a different workbook. Ill give an example lets say i have an excel file called "test1", This file has some references from another workbook called "test2" The following code only applies from the workbook from "test1"

   lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' will get the last row
   MsgBox (lastRow) 'wrote this for debugging purposes
   Worksheets("SalesContest").Range("A3:A" & lastRow).Clear

I have this code so it can clear the contents for row A only in "test1" file But the problem comes when I randomly open "test2" and somehow it runs the code above on "test2" even though its suppose to run only on "test1" So when i open "test2" there is a messagebox that says the number of rows in "test2" and it also gives me the following error message "RUn time error 9" Subscript out of range" Is there a way i can fix this so it doesnt call "test2" but only "test1"

Upvotes: 0

Views: 518

Answers (1)

iDevlop
iDevlop

Reputation: 25272

You can use ThisWorkbook.Worksheets("SalesContest").Range("A3:A" & lastRow).Clear to make sure it's applying to the workbook where the code is running.

Upvotes: 1

Related Questions