vba - Subscript out of range when copying worksheet -
i create command button imports selected file current workbook.
i'm getting subscript out of range error
, cannot find out solution.
here have:
private sub cmdbrowsefile_click() dim intchoice, total integer dim file, controlfile string controlfile = activeworkbook.name 'only allow user select 1 file application.filedialog(msofiledialogopen).allowmultiselect = false 'remove other filters call application.filedialog(msofiledialogopen).filters.clear 'add custom filter call application.filedialog(msofiledialogopen).filters.add( _ "text files only", "*.xlsx") 'make file dialog visible user intchoice = application.filedialog(msofiledialogopen).show 'determine choice user made if intchoice <> 0 'get file path selected user file = application.filedialog( _ msofiledialogopen).selecteditems(1) 'open file workbooks.open filename:=file total = workbooks(controlfile).worksheets.count workbooks(file).worksheets(activesheet.name).copy _ after:=workbooks(controlfile).worksheets(total) windows(file).activate activeworkbook.close savechanges:=false windows(controlfile).activate end if
error :
the error occurs on line
workbooks(file).worksheets(activesheet.name).copy...
because workbooks(<argument>)
expecting name of file, without full path. parsing full path.
fixed code
private sub cmdbrowsefile_click() dim intchoice integer, total integer 'note correct declaring, each variable type dim strfilepath string, strcontrolfile string dim strfilename string strcontrolfile = activeworkbook.name 'only allow user select 1 strfilepath application.filedialog(msofiledialogopen).allowmultiselect = false 'remove other filters call application.filedialog(msofiledialogopen).filters.clear 'add custom filter call application.filedialog(msofiledialogopen).filters.add( _ "text files only", "*.xlsx") 'make strfilepath dialog visible user intchoice = application.filedialog(msofiledialogopen).show 'determine choice user made if intchoice <> 0 'get strfilepath path selected user strfilepath = application.filedialog( _ msofiledialogopen).selecteditems(1) 'get file name strfilename = dir(strfilepath) 'open strfilepath workbooks.open filename:=strfilepath total = workbooks(strcontrolfile).worksheets.count workbooks(strfilename).worksheets(activesheet.name).copy _ after:=workbooks(strcontrolfile).worksheets(total) windows(strfilename).activate activeworkbook.close savechanges:=false windows(strcontrolfile).activate end if end sub
notes
the main change dim strfilename string
, strfilename = dir(strfilepath)
, it's usage in code after opening new book. changed variables names test purposes, can read more way. can use rename tool revert changes.
Comments
Post a Comment