简体   繁体   中英

Subscript out of range with sheet reference from cell value

I get this message with the following block of code. I know I'm not defining my range correctly but I'm a bit lost. Thanks!

 Sub clean_data()


Dim Preliminary_MTM As Worksheet
Dim Sheetlink As String

Sheetlink = Worksheets("Input for model").Range("E17").Value

Set Preliminary_MTM = Sheets(Sheetlink)

Preliminary_MTM.Activate

Based on your comment that the contents of cell "E17" is exactly Worksheets("Preliminary MTM Q1") then you would have to have a worksheet named "Worksheets("Preliminary MTM Q1")" (ie that's what you would see on the worksheet tab in your Excel file) and my guess is you don't have one with that name. As a matter of fact, you can't have a worksheet with that name because it's too long:

在此处输入图片说明

What you want in E17 is simply Preliminary MTM Q1 so that when you reference it in this code:

Set Preliminary_MTM = Worksheets(Worksheets("Input for model").Range("E17").Value2)

it accesses the contents of that cell and looks for the worksheet named there.

Note: I've changed .Value for .Value2 . .Value2 gives you the completely unformatted text in the cell, while .Value will return formatting information - this can cause problems.

Note: I've reduced the code to the one line because that's all that's necessary. If you're actually using the variable sheetlink elsewhere, then you'll need to include that.

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