简体   繁体   中英

Extract a Range Value and assign to a String Variable

I would like to extract a range value and assign it to a string variable.

In the following image, the value that I would like to store to a string variable is from Range("E10:J11").Value(1,1) which holds the string "Disputes/Appeals".

Range values

The codes that I used for implementation are:

Dim P3 As String

'This line gives me Run-time error '13'
'Type mismatch
P3 = Worksheets("NameofmySheet").Range("E10:J11").Value

Having this error, I knew that I need to be specific to the arguments of .Value so that my assignments would agree to the same data type.

Based from the image, following the Range("E10:J11").Value(1,1) specification, here is what I did:

'This line gives me Run-Time error '450'
'Wrong number of arguments or invalid property assignment
P3 = Worksheets("NameofmySheet").Range("E10:J11").Value(1, 1)

Now I think I am on the right track but I could just not find out the correct syntax or the proper arguments for this type of assignment.

Range.Value returns a Variant (which is basically a "container" type that can hold pretty much anything). If there is only one cell in the Range , it will contain the underlying contents of the cell. If there is more than one cell in the Range , it returns a 2 dimensional array of Variant , with each element containing the underlying contents of one cell. It can also return a Variant of type vbEmpty or vbError if the cell doesn't contain anything or has a formula that results in an error.

When you access this .Value ...

Worksheets("NameofmySheet").Range("E10:J11").Value

...you get a 2D array. That is the reason why your screenshot is showing array indexes.

The reason why this code...

P3 = Worksheets("NameofmySheet").Range("E10:J11").Value(1, 1)

...doesn't work, is that .Value is actually an indexed property with an optional RangeValueDataType parameter. So the compiler interprets the (1, 1) the index. Since you're passing 2 "parameters", you get the "Wrong number of arguments" error.

Although the other answers show different ways of getting the value of the target cell, in order to apply indexing to the return value of .Value using property return/array index syntax, you need to explicitly provide an empty parameter list to .Value :

P3 = Worksheets("NameofmySheet").Range("E10:J11").Value()(1, 1)
                                                      '^^

Note, this syntax...

P3 = Worksheets("NameofmySheet").Range("E10:J11")(1, 1).Value

...provides the index to the Range parameter instead, which returns a one cell Range , which has the .Value called on it .

您想将(1,1)放在.Value前面:

P3 = Worksheets("NameofmySheet").Range("E10:J11")(1, 1).Value

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