1

I'm trying to import Csv file to excel using VBA code, I want it to work with all Csv files but it didn't. Here is my code:

Sub Input_CSV()

Dim Wb As String
Dim Arr

    Set Wb = GetObject(Application.GetOpenFilename("csv file,*.csv", , "please choose a csv file", , False))

    Dim blnImportData As Boolean
    blnImportData = ImportCSV(Wb, "Sheet1", "A1")
    If blnImportData Then MsgBox "Import CSV process complete", vbInformation, ThisWorkbook.Name _
    Else MsgBox "Import CSV process failed", vbCritical, ThisWorkbook.Name

End Sub

And here is the function code

Function ImportCSV(ByVal Filename As String, _
                   ByVal Worksheet As String, _
                   ByVal StartCell As String) As Boolean
 On Error GoTo Catch

    Dim strConnectionName As String
    strConnectionName = "TEXT;" + Filename

    With Worksheets(Worksheet).QueryTables.Add(Connection:=strConnectionName, _
                                               Destination:=Worksheets(Worksheet).Range(StartCell))
        .Name = Filename
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlOverwriteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True 'False
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = True 'False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .Refresh BackgroundQuery:=False
    End With

        ImportCSV = True
        Exit Function

Catch:
        ImportCSV = False

End Function

How could I correct it? Could someone help me plz!

Community
  • 1
  • 1
shinpencil
  • 43
  • 1
  • 2
  • 9
  • It is difficult to offer solutions when the problem statement is simply, "it doesn't work". Please [edit] your question to give a more complete description of what you expected to happen and how that differs from the actual results. See [ask] for hints on what makes a good explanation. – Toby Speight Jun 13 '16 at 08:55
  • I couldn't edit so I'm trying to answer here.I have a bug in this line: "blnImportData = ImportCSV(Wb, "Sheet1", "A1")", error 438: object doesn't support this property or method – shinpencil Jun 13 '16 at 09:23
  • You only need to use `Set` where you define an object reference. Since `Wb` is a string, you don't use `Set` – Dave Jun 13 '16 at 09:54
  • I erased "Set" but I still got the same mistake – shinpencil Jun 13 '16 at 10:07

2 Answers2

2

You have a good explanation here:

https://sitestory.dk/excel_vba/csv-file-import.htm

with the code I applied in my case:

 Sub OpenCSV()

 Dim sPath As String
 sPath = ThisWorkbook.Path & "\Site_survey_form2.csv"
 Workbooks.OpenText Filename:= _
 sPath, DataType:=xlDelimited, Semicolon:=True, Local:=True
 End Sub

As a result, the .csv file will be opened in the separate workbook.

If you want to import the .csv content straight away to your workbook, then I would advise referring to the thread here:

Is there a way to import data from .csv to active excel sheet?

from where I prepared the following code:

 Sub CSV_Import()
 Dim ws As Worksheet, strFile As String, sPath As String

 Set ws = ActiveWorkbook.Sheets("Sheet1") 'set to current worksheet name

 sPath = ThisWorkbook.Path & "\Site_survey_form2.csv"  '"\ your file name

  With ws.QueryTables.Add(Connection:="TEXT;" & sPath, 
  Destination:=ws.Range("A1"))  
 .TextFileParseType = xlDelimited
 .TextFileCommaDelimiter = True
 .Refresh

End With End Sub

Geographos
  • 827
  • 2
  • 23
  • 57
1

You could simplify and use the following to open your file:

Public Sub OpenCsvFile(byVal filepath)
    Workbooks.OpenText filename:=filepath, dataType:=xlDelimited, semicolon:=True
End Sub

More details on this method here (MSDN link)

Dave
  • 4,328
  • 2
  • 24
  • 33