简体   繁体   中英

How to open a file with a variable extension in vba excel

I have to made a vba for open a CSV from excel the problem is the files has a format:

constan_name_file . YYY

For example

file1.124514 (Day 1)

file1.144521 (Day 2)

file1.152132 (Another day)

The name file is a constan but the YYY is variable, but the file inside is a CSV. thats possible to open it?

I've had a problem to keep the formatting when opening a csv-file in Excel 2007. Looked around in excel-forums only to find one possible solution. Change file-extension from csv to txt.

Tried to make a Function as general as possible. Here it is:

Option Explicit

Function ChangeFileExt(filnamn As String, extensionOld, extensionNew)         
Dim oldname, newname as string     

oldname = ThisWorkbook.Path & "\" & filnamn & "." & extensionOld

newname = ThisWorkbook.Path & "\" & filnamn & "." & extensionNew         
Name oldname As newname  

End Function

'...............................................................................

Sub change_extension()     

' Objective: Want to keep csv-format at workbook.open

' Rename file from filename.csv to filename.txt      
' Open txt-file            
' process data          
' Rename back to csv-file if neccesary        


Dim csv, txt As String           

csv = "csv"      
txt = "txt"         

Call ChangeFileExt("file_name_to_change", csv, txt)      '  omit extension in file_name_to_change         

...all kinds of code       

Call ChangeFileName("file_name_to_change", txt, csv)      '  change filename back to original name


End Sub

Why dont you forcefully open it as a CSV file

Workbooks.Open Filename:=name, Format:=2

Here the 2 specifies that the file is comma delimited http://msdn.microsoft.com/en-us/library/office/ff194819.aspx

Yes, try the below code:

dim sFileName as string
dim sExtension as string

sExtension="YYY"
sfilename=constan_name_file & "." & sExtension

workbooks.open sfilename, Format:=2

Thanks for the use of Wildcards, finally I get the code.

sub GetFiles(direc As String, fich As String) 

    Dim strFileName As Variant

    strFileName = dir(direc & "\" & fich & ".******")

       If Len(strFileName) > 0 Then
        'open
       end if

End sub

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