Home > Blockchain >  VBA - FileTo-Open a .csv file
VBA - FileTo-Open a .csv file

Time:02-17

I have this code to open a file and then copy data from that file into my active file. The file I am opening is an excel csv file and it is the first time I am trying to use the FileToOpen to import files from a csv but with the window opens to select the file, I cannot see the csv files. I am not extremely experienced using this function but it has worked just fine with .xls files. Any help is appreciated. The image below is are the properties of the file I am looking for.

enter image description here

FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="CSV (*.csv*),*csv*")
If FileToOpen <> False Then
   Set OpenBook = Application.Workbooks.Open(FileToOpen)
   OpenBook.Sheets(1).Range("A2:N5000").Copy
   ThisWorkbook.Worksheets("TMS_CLOSED_OUTBOUND_AND_POWER_S").Range("A2:N5000").Value = OpenBook.Sheets(1).Range("A2:N5000").Value
   OpenBook.Close False
End If

CodePudding user response:

The function is FileFilter:="CSV (.csv),.csv"); change the FileFilter parameter as follows:

FileFilter:="CSV (*.csv),*.csv")

to browse files with extension .csv.

Once the dialog opens, make sure that you navigate to c:\users\2246332\temp files folder as your screenshot indicates; the CSV files, if any, should show.

CodePudding user response:

Copy Range Values From a Closed Workbook (GetOpenFilename)

Option Explicit

Sub CopyRange()
 
    Const sgofTitle As String = "Browse for your File & Import Range"
    Const sgofFileFilter As String = "CSV Files (*.csv), *.csv"
    Const sgofMultiSelect As Boolean = False
    Const srgAddress As String = "A2:N5000"
    
    Const dName As String = "TMS_CLOSED_OUTBOUND_AND_POWER_S"
    Const dfcAddress As String = "A2"
    
    Dim sFilePath As String
    sFilePath = Application.GetOpenFilename( _
        sgofFileFilter, , sgofTitle, , sgofMultiSelect)
    If sFilePath = "False" Then
        MsgBox "You canceled.", vbExclamation
        Exit Sub
    End If
    
    Dim swb As Workbook: Set swb = Workbooks.Open(Filename:=sFilePath)
    ' When saving, my CSV files get saved with the semicolon as the separator,
    ' because the semicolon is my default list separator. When opening them,
    ' they get opened with all the delimited data in column 'A'.
    ' To prevent this, I need to open CSV files with 'Local:=True':
    'Set swb = Workbooks.Open(Filename:=sFilePath, Local:=True)
    Dim srg As Range: Set srg = swb.Worksheets(1).Range(srgAddress)
    
    Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
    Dim dfCell As Range: Set dfCell = dwb.Worksheets(dName).Range(dfcAddress)
    Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
   
    drg.Value = srg.Value
    swb.Close SaveChanges:=False
    'dwb.Save
    
    MsgBox "Range copied.", vbInformation

End Sub
  • Related