I have written a macro module to aid users import .csv files into some empty tables ready for further analysis. These .csv files always contain three columns of data, but the amount of rows varies greatly and can be in the thousands. Previously we used to copy and paste values, but this is notoriously slow. Instead we have switched to using ''Range.Value ='' (shown in green below).
This has sped things up massively, but I am struggling to size the receiving table to match the amount of rows from the incoming data set. As a work around I have just manually set, using a resize function, to a value that I know to be larger than the amount of rows in the data set (shown in blue below and set in this example to 100 rows). This will then just show any empty rows as #N/A. Not pretty!
I could write some code to remove the #N/A rows, but I am sure there must be a neater way to do this from the off. Can anyone let me know how to code this so each table will match the size of their imported data set? I have attached a striped down version of the macro file along with a test .csv file to allow you to try this out. Thanks in advance for any help.
Sub Data_IMPORT_CSV()
Dim ToSheet As Worksheet
Dim FromBook As String
Dim FromSheet As Worksheet
Dim RngT1 As Range, RngT2 As Range
Dim RngF1 As Range, RngF2 As Range
Dim TableRng As Range
'-------------------------------------------------------------------------
On Error Resume Next
Set ToSheet = ActiveSheet
FromBook = Application.GetOpenFilename("CSV (*.csv), *.csv, All Files (*.*), *.*")
'They have cancelled.
If FromBook = "False" Then Exit Sub
Workbooks.Open FromBook, Local:=True
Set FromSheet = ActiveWorkbook.Sheets(1)
'COPY & PASTE DATA **Coulmn A**
ActiveSheet.Range("A1").Select
ActiveSheet.Range(ActiveCell.Offset(0, 0), ActiveCell.End(xlDown)).Select
Set RngF1 = Selection
ToSheet.Activate
Selection.ListObject.HeaderRowRange.Find("Type").Offset(1, 0).Resize(100, 1).Select 'Find the named range & pastes
Set RngT1 = Selection
RngT1.Value = RngF1.Value
'COPY & PASTE DATA 2 **Column C**
FromSheet.Activate
ActiveSheet.Range("C1").Select
ActiveSheet.Range(ActiveCell.Offset(0, 0), ActiveCell.End(xlDown)).Select
Set RngF2 = Selection
ToSheet.Activate
Selection.ListObject.HeaderRowRange.Find("Value").Offset(1, 0).Resize(100, 1).Select 'Find the named range & pastes
Set RngT2 = Selection
RngT2.Value = RngF2.Value
'CLOSE FROMBOOK
Workbooks(2).Close SaveChanges:=False
If Err Then MsgBox "No table selected!": Err.Clear 'display this message if the above fails
MsgBox ("DONE")
End Sub
Bookmarks