简体   繁体   中英

VBA EXCEL - open file and assign path to a new workbook path

there. i'm trying to pass a file path for defining a new workbook's path... All seems fine until I get a "Subscript out of range" at the line:

Set rngS = Workbooks(wkbS).Range("myRange1")

I've reduced the original file name length, as well as for its folder directory name, etc... I've also switched type definitions between string, variant, etc... I'd appreciate any suggestions. txs a lot.

错误

Sub myMain()

dim wkbS as string
dim rngS as range

wkbS = open_file_src
Debug.Print "w_source_path is : " & wkbS

Set rngS = Workbooks(wkbS).Range("myRange1")      
debug.print "Range rngS : " & rngS.address
End Sub


Function open_file_src() As String
   
    strFile_src = Application.GetOpenFilename(filefilter:="Excel files,*.x*", Title:="Select SOURCE file")
    Workbooks.Open Filename:=strFile_src
    Debug.Print "open_file_src PATH is : " & strFile_src
    
    open_file_src = strFile_src
        
End Function

You have to pass the name of the target Workbook without it's path as it is open on Excel:

wkbS="ChoosedWorkbook.xls"

And then there are two ways to set rngS range:

Set rngS =  = Workbooks(wkbS).Names("myRange1").RefersToRange

or, passing the sheet name wich contains the target range:

Set rngS = Workbooks(wkbS).Sheets("theNameOfTheSheet").Range("myRange1")

The modified code to get the filename:

Function open_file_src() As String
   Dim strFile_src As String
    strFile_src = Application.GetOpenFilename(filefilter:="Excel files,*.x*", Title:="Select SOURCE file")
    Workbooks.Open Filename:=strFile_src
    Debug.Print "open_file_src PATH is : " & strFile_src
    
    open_file_src = Right(strFile_src, Len(strFile_src) - InStrRev(strFile_src, "\"))
        
End Function

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