21

I have a csv file always named the same, called SO2PO.csv. It has data that I import into an excell sheet called PO Data, in a workbook called Open Order. I need to find a way to import all the data from SO2PO.csv to Open Order.xlsm sheet PO Data.

I know it's possible, but how? Can someone point me in the right direction?

Or is there a way to make it so that I can import any .csv file that in placed into a specific folder?

Community
  • 1
  • 1
Matt Ridge
  • 3,633
  • 16
  • 45
  • 63
  • 3
    I hate to say this, but I specifically said I am attempting this into an Excel sheet...I figured that, plus the tags, excel, and excel-vba would be indications that Excel was the application I was using and that Excel-VBA was a possibility...for a solution. If I was going to do this using another app, I probably would of said... – Matt Ridge Aug 30 '12 at 13:00
  • Yes, it was evident that Excel was the application. It was not evident the *external* mechanism you desired to use, whether that might have included writing a separate, standalone app in something like C# or VB.Net, or perhaps as part of a larger application using SQL Server. You know your system. We don't. I really enjoy helping here, but responses like this when trying to provide the help aren't very encouraging. Good luck with your project. – David W Aug 30 '12 at 13:19
  • 2
    If there was going to be C# and VB.Net I would of put that in the tags... I'm pretty litteral when I ask for things. – Matt Ridge Aug 30 '12 at 13:49

5 Answers5

43

Add this code to create a QueryTable in the PO Data sheet to your data source

Once you have created the QueryTable you can then just right click Refresh the data (or refresh on open)

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

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

strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please select text file...")

With ws.QueryTables.Add(Connection:="TEXT;" & strFile, Destination:=ws.Range("A1"))
     .TextFileParseType = xlDelimited
     .TextFileCommaDelimiter = True
     .Refresh
End With
End Sub
kevinarpe
  • 20,319
  • 26
  • 127
  • 154
Steve
  • 1,620
  • 2
  • 19
  • 33
  • The only reason I ask is because when I try and change the files to xlxs or xls a lot of extr acode gets thrown into it. – Matt Ridge Aug 30 '12 at 14:31
  • 1
    Connecting to an excel file is not the same method, but is doable using ADO connection. I think that it would require another question to answer rather than here in comment. – Steve Aug 30 '12 at 15:04
  • Just curious, turns out the file I was looking at wasn't even an xls file, but was renamed it... – Matt Ridge Aug 30 '12 at 15:12
9

If you're going to use querytables make sure you clean up after, leftover query tables caused me a few headaches in a downstream process.

' get the file to the data sheet
Set ws = ActiveWorkbook.Sheets("Data")
With ws.QueryTables.Add(Connection:="TEXT;" & "mydata.csv", Destination:=ws.Range("A1"))
    .TextFileParseType = xlDelimited
    .TextFileCommaDelimiter = True
    .Refresh
End With

' delete the querytable if there is one
On Error GoTo nothingtodelete
    Sheets("Data").QueryTables(1).SaveData = False
    Sheets("Data").QueryTables.Item(1).Delete 
nothingtodelete:
hatchnet
  • 111
  • 1
  • 5
3

There are lots of ways to get data into Excel. Querytables (as demonstrated by The_Barman), SQL, Import Wizard etc.

Usually the method depends on how clean the data is presented on the files you need to import and if you know exactly how it's laid out. Eg if there are empty rows, mixed data types, merged cells etc then it can be a nightmare.

Below is a slower 'brute-force' method which will usually get all data by opening the file in Excel first. It's often the last thing to do when other methods fail.

Option Explicit

Public Sub ImportData()
Dim CSVFilename As String
Dim writeToFilename As String
Dim writeToSheet As String
Dim readXL As Workbook
Dim readWS As Worksheet
Dim writeXL As Workbook
Dim writeWS As Worksheet
Dim UsedRng As Range



    CSVFilename = Environ$("USERPROFILE") & "\Desktop" & "\SO2PO.csv"
    writeToFilename = Environ$("USERPROFILE") & "\Desktop" & "\Open Order.xlsx"
    writeToSheet = "PO Data"


    Set writeXL = GetObject(writeToFilename)
    Set writeWS = writeXL.Sheets(writeToSheet)
    'writeWS.Parent.Windows(1).Visible = True


    Set readXL = GetObject(CSVFilename)

    With readXL

        Set readWS = readXL.Sheets(1)
        Set UsedRng = RealUsedRange(readWS)
        writeWS.Range(UsedRng.Address).Value = UsedRng.Value

    End With

    'close CSV without saving
    readXL.Close SaveChanges:=False
    Set readWS = Nothing
    Set readXL = Nothing

    'close template with save
    writeXL.Close SaveChanges:=True
    Set writeWS = Nothing
    Set writeXL = Nothing


End Sub


Public Function RealUsedRange(ByVal WS As Worksheet) As Range
'Find used range
    Dim FirstRow        As Long
    Dim LastRow         As Long
    Dim FirstColumn     As Integer
    Dim LastColumn      As Integer

    On Error Resume Next

    With WS

        FirstRow = .Cells.Find(What:="*", After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlValues, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row

        FirstColumn = .Cells.Find(What:="*", After:=.Cells(.Rows.Count, .Columns.Count), LookIn:=xlValues, LookAt:= _
        xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column

        LastRow = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

        LastColumn = .Cells.Find(What:="*", After:=.Range("A1"), LookIn:=xlValues, LookAt:= _
        xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

        Set RealUsedRange = .Range(.Cells(FirstRow, FirstColumn), .Cells(LastRow, LastColumn))

    End With

    On Error GoTo 0

End Function
2

it is possible.

Without vba you would use the DATA-Tab and import from text source.

With vba you could open the csv as a new Workbook:

Public Function openSource(fileToOpen As String) As Excel.Workbook
On Error GoTo err_exit

    Dim f As Object
    Dim fs As Object

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set openSource = Nothing

    If fs.fileexists(fileToOpen) Then
        Set f = fs.GetFile(fileToOpen)

        Set openSource = ThisWorkbook.Application.Workbooks.Open( _
            FileName:=f.path, _
            UpdateLinks:=2, _
            ReadOnly:=True, _
            AddToMRu:=False, _
            Notify:=False)

        Windows(openSource.Name).Visible = False
    End If
    Exit Function
err_exit:
    'throwErrMsg "Failed to read File!", "openSource"
    If Not openSource Is Nothing Then
        openSource.Close SaveChanges:=False, RouteWorkbook:=False
    End If
End Function

Dim CSVWorkbook As New Excel.Workbook
Set CSVWorkbook = openSource(c:\SO2PO.csv)

Now you can navigate through this workbook like any other and copy rows, cols or a whole worksheet ;) hope this helps.

Another way would be to use the import from text in vba version, but i don't have an example right away.

Jook
  • 4,564
  • 3
  • 26
  • 53
1
Sub demo()
Dim FilePath As String
FilePath = "C:\Users\Tamil\Desktop\padding_values.csv"
Open "C:\Users\Tamil\Desktop\padding_values.csv" For Input As #1
row_number = 0
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, ",")
ActiveCell.Offset(row_number, 0).Value = LineItems(2)
ActiveCell.Offset(row_number, 1).Value = LineItems(1)
ActiveCell.Offset(row_number, 2).Value = LineItems(0)
row_number = row_number + 1
Loop
Close #1


End Sub
Tamil Selvan S
  • 562
  • 8
  • 25