简体   繁体   中英

Run Time error 9

I have created a workbook which is named "AirHours" & the date from another workbook. I want to use this workbook throughout the entire project. The code below works, but I keep getting a run-time error 9 "Subscript out of range".

I'm trying to create a workbook for my report and have my data remain in its original form. The new workbook will be used in a number of modules. The runtime error seems to occur at SET WSD3=Workbook .

Maybe I going the wrong way on creating a public workbook. Thanks for your help.

Option Explicit

Public WSD3 As Workbook

Public Sub addNewWorkBook()

Dim NewName As String

Application.DisplayAlerts = False

NewName = "AirHours" & Workbooks("AirTimeWorkBookBeta").Worksheets("Data").Cells(2, 1).Value

Workbooks.Add

ActiveWorkbook.SaveAs NewName
Set WSD3 = Workbooks("NewName")


End Sub

Set WSD3 to your new workbook when you open it

Option Explicit

Public WSD3 As Workbook

Public Sub addNewWorkBook()

Dim NewName As String

Application.DisplayAlerts = False

NewName = "AirHours" & Workbooks("AirTimeWorkBookBeta").Worksheets("Data").Cells(2, 1).Value

Set WSD3 = Workbooks.Add

WSD3.SaveAs NewName


End Sub

Along with scott's suggestion, part of the problem is that when referencing workbooks with Workbooks("workbookname.ext") you need to provide the extension, like .xls or .xlsm, so you'll need to update the where you're referencing Workbooks("AirTimeWorkBookBeta") to include that workbook's appropriate extension.

You could also get the error if that workbook isn't currently open when the macro is run. Additionally, make sure that workbook contains a sheet named Data

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