how to avoid runtime error while displaying a message box in excel vba -


i trying display message box saying "file not chosen" if file not chosen.my problem message box getting displayed when click on ok runtime error 1004 saying "file not found or check spelling , location of file".can me how avoid error.thank you

dim wbk1 workbook, wbk2 workbook, wbk3 workbook dim sh1 worksheet, sh2 worksheet, sh3 worksheet dim tmp1 string, tmp2 string, tmp3 string dim textbox1 string dim textbox2 string dim textbox3 string   tmp1 = sheets("sheet1").textbox1.value if len(trim(tmp1)) = 0 msgbox "file not chosen" end if exit sub tmp2 = sheets("sheet1").textbox2.value if len(trim(tmp2)) = 0 msgbox "destination file not selected" end if exit sub tmp3 = sheets("sheet1").textbox3.value if len(trim(tmp3)) = 0 msgbox "mapping file not selected" end if exit sub   set wbk1 = workbooks.open(tmp1) set wbk2 = workbooks.open(tmp2) set wbk3 = workbooks.open(tmp3)  set sh1 = wbk1.sheets("inventory") set sh2 = wbk2.sheets("inventory") set sh3 = wbk3.sheets("sheet1") 

as john mentioned, have use exit for. using them @ wrong place.

also bad idea declare control variable. yes, referring

dim textbox1 string dim textbox2 string dim textbox3 string 

try this

sub sample()     dim wbk1 workbook, wbk2 workbook, wbk3 workbook     dim sh1 worksheet, sh2 worksheet, sh3 worksheet     dim tmp1 string, tmp2 string, tmp3 string      tmp1 = thisworkbook.sheets("sheet1").textbox1.value      if len(trim(tmp1)) = 0         msgbox "file not chosen"         exit sub     end if      tmp2 = thisworkbook.sheets("sheet1").textbox2.value      if len(trim(tmp2)) = 0         msgbox "destination file not selected"         exit sub     end if      tmp3 = thisworkbook.sheets("sheet1").textbox3.value      if len(trim(tmp3)) = 0         msgbox "mapping file not selected"         exit sub     end if      set wbk1 = workbooks.open(tmp1)     set wbk2 = workbooks.open(tmp2)     set wbk3 = workbooks.open(tmp3)      set sh1 = wbk1.sheets("inventory")     set sh2 = wbk2.sheets("inventory")     set sh3 = wbk3.sheets("sheet1") end sub 

after doing this, if still message "file not found or check spelling , location of file" means path mentioned in textbox not correct. can use dir check if path correct or not.

for example

 if dir(tmp1) = ""      msgbox "incorrect path/file. please ensure textbox has correct path"  else      set wbk1 = workbooks.open(tmp1)  end if 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -