Use Excel VBA to select and open a file

Source: Internet
Author: User

This section describes how to use VBA to select a file and use VBA to open a file.
Clicking open file will pop up a Windows File opening dialog box. In Excel, how does VBA implement this function?

 

Sub selectfile ()
Dim filename as Variant
'The file name returned by the open file dialog box is a full-path file name. Its value may also be false, so the type is variant.
File Name extracted from filename by dim sfilename as string'
Dim spathname as string 'path name extracted from filename
Dim afile as variant array, used to extract the file name sfilename
Dim ws as worksheet ': the worksheet that stores the file path name and file name
Set Ws = worksheets ("sheet1") 'sets the worksheet
Filename = application. getopenfilename ("Excel file (*. xls), *. xls ")
'Call the windows open file dialog box
If filename <> false then' is not pressed
Afile = Split (filename, "/") 'in the full path, with the separator "/", divided into data
Spathname = afile (0) 'Drive letter
For I = 1 to ubound (afile)-1 'loop synthesis path name
Spathname = spathname & "/" & afile (I)
Next
Sfilename = afile (ubound (afile) 'the last element of the array is the file name
WS. cells (1, 2). value = spathname 'Save the path name
WS. cells (2, 2). value = sfilename 'save the file name
End if
End sub does not actually open the file after it is selected to open it.

For how to securely open an Excel file, see open a file with High Fault Tolerance

For examples of this file, see batch export TXT files from any Excel File

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.