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