Unable to set excel VBA worksheet variable

ぐ巨炮叔叔 提交于 2019-12-02 20:59:20

问题


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


回答1:


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")


来源:https://stackoverflow.com/questions/54060861/unable-to-set-excel-vba-worksheet-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!