简体   繁体   中英

Assign worksheet range using a string variable

I have a string variable with the following value assigned:

Answer = ""M3:AM3""

I want to assign this variable to a Range as follows:

DIM xlRange As Excel.Range
Set xlRange = xlApp.Sheets("Sheet1").Range(Answer)

This generates the error "Application-defined or object-defined error"

I also tried the following to paste values using the variable for the range and got the same error:

xlApp.Sheets("Sheet1").Range(Answer).PasteSpecial xlPasteAll

Can someone please help me resolve this? Thanks.

I think your error is the xlApp, which is not defined:

DIM xlApp as Excel.Application

If you have already have it defined, then the problem is the double quote, which does not mean anything to VBA. Also you have another problem which is the hierarchy:

 xlApp.Sheets("Sheet1").Range(Answer)

after xlApp you have to define a WORKBOOK and not a WORKSHEET. So you need to give the workbook of Sheet1 too

so Assuming:

Answer="M3:AM3"

you can write:

 Set xlApp = Application
 Set xlRange = xlApp.ActiveWorkbook.Sheets("Sheet1").Range(Answer)

If you know the name of the workbook for certain, then you can replace ActiveWorkbook with Workbooks("MyWorkbookName").

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