简体   繁体   中英

Assign range from a different workbook to variable

I want to use the WorksheetFunction.Match function, and need to load this with an area.

Row = WorksheetFunction.Match(country, Countries, 0)

Can you help me construct the Countries variable? I tried lots of ways (including the below) but none seem to work...

Countries = Workbooks("PERSONAL.XLSB").sheets("Sheet1").Range("B:B") 
Countries = Worksheets("PERSONAL.XLSB!Sheet1").Range("B:B") 
Countries = Worksheets.Range("PERSONAL.XLSB.Sheet1!B:B")  ...

I also tried some of the above with "Set" in front but that didn't help either...

Well I used the code below and it works OK. You do have a PERSONAL.XLSB file which is loading and hidden when you start Excel? What is the error message - is it subscript out of range?

Public Sub test()

 Dim r As Integer
 Dim Countries As Range
 Dim Country As Range

 Set Countries = Workbooks("PERSONAL.XLSB").Worksheets("Sheet1").Range("C1:C8")
 Set Country = Workbooks("PERSONAL.XLSB").Worksheets("Sheet1").Range("A1")

 r = WorksheetFunction.Match(Country, Countries, 0)

 MsgBox (r)

End Sub

OK problem solved, thanx Dave!

I actually use it as a Function that returns the "area" to which the country belongs:

Function AreaEMEA(Country As String)
 Dim Countries As Range
 Dim Areas As Range
 Set Countries = Workbooks("PERSONAL.XLSB").Worksheets("Sheet1").Range("B:B")
 Set Areas = Workbooks("PERSONAL.XLSB").Worksheets("Sheet1").Range("A:A")
 Row = WorksheetFunction.Match(Country, Countries, 0)
 AreaEMEA = WorksheetFunction.Index(Areas, Row)
End Function

which i call using

"=PERSONAL.XLSB!Module1.areaemea(A1)"

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