I am currently working on my first try on excel macros and probably not picked an easy start. I want to import specific columns from all .csv files in one folder (always the same column letter) into one excel sheet. So there are two columns of interest at the moment and I want to have one sheet for each csv column and all files as new excel columns. So 50 csv files with two .csv columns of interest would result into one excel file with two sheets and 50 columns each. I have tried a few things and the macro is currently looking like below. It is meant to pick up all .csv files from a directory, then select the column B from row 2 to number of rows used and copy this, then switch to the excel file and paste it into the next empty column where the header is set as the .csv filename and all data pasted below. Same shiuld be done for .cs column F. Afterwards the .csv file should be closed and the next one openend until files of the directory are processed. Currently the macro is failing in line 27: Windows(f.Name).Activate Giving 'runtime error 9 - index out of range'
Sub csv_imp()
'
' csv_imp Makro
'
' Tastenkombination: Strg+r
'
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim xl As New Excel.Application
Dim wb As New Excel.Workbook
Dim lastColumn
Dim folder
Dim rng As Range
Dim res As Workbook
Dim target As Range
Set folder = fso.getFolder("C:\data\")
Set res = Workbook("Results")
Set lastColumn = 0
For Each f In folder.Files
Debug.Print f.Name
If (f.Name Like "*.csv") Then
Set rng = Range("B2:B60")
rng.Copy
Windows("Results").Activate
Set wb = xl.Workbooks.Open(f.Path)
wb.Sheets(1).Range(ColumnLetter(lastColumn + 1) & "1").Value = f.Name
Set target = wb.Sheets(1).Range(ColumnLetter(lastColumn + 1) & "2")
target.Paste
lastColumn = lastColumn + 1
wb.Save
f.Close
End If
Next
xl.Quit
End Sub
Function ColumnLetter(ByVal ColumnNumber As Long) As String
Dim n As Long
Dim c As Byte
Dim s As String
n = ColumnNumber
Do
c = ((n - 1) Mod 26)
s = Chr(c + 65) & s
n = (n - c) \ 26
Loop While n > 0
ColumnLetter = s
End Function
It would be great if someone could help :) Seb