简体   繁体   中英

Unable to set excel VBA worksheet variable

I am trying to set a source worksheet variable to a target worksheet variable in another workbook(DataSource1.xlsx) with the purpose of eventually using it to read the target worksheet and perform some calculation but it gives me the subscript out of range error.

This is my code

Sub GenerateReport()

Dim source As Worksheet

Dim path As String    
Set source= Workbooks(ThisWorkbook.path & "\DataSource1.xlsx").Sheets("Sheet1")

'path = ThisWorkbook.path

'Set wb = Workbooks.Open(ThisWorkbook.path & "\DataSource1.xlsx")

Dim one As Integer

one = 10

End Sub

The file are all placed in the same folder and I have checked that there are no naming or path errors, why is this happening?

EDIT

This is what my project looks like after GSerg comments

在此处输入图片说明

If the workbook is already opened, you need to refer to it by name without path:

Set source = Workbooks("DataSource1.xlsx").Sheets("Sheet1")

If the workbook is not opened yet, you need to open it first:

Set source = Workbooks.Open(ThisWorkbook.path & "\DataSource1.xlsx").Sheets("Sheet1")

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