简体   繁体   English

使用字符串变量分配工作表范围

[英]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: 我想将此变量分配给Range,如下所示:

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: 我认为您的错误是未定义的xlApp:

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. 如果已经定义了它,那么问题在于双引号,这对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. 在xlApp之后,您必须定义一个WORKBOOK,而不是WORKSHEET。 So you need to give the workbook of Sheet1 too 所以您也需要提供Sheet1的工作簿

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"). 如果您肯定知道工作簿的名称,则可以将ActiveWorkbook替换为Workbooks(“ MyWorkbookName”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM