VBA:将csv中的行复制到新工作表中的列中

时间:2017-01-25 20:22:04

标签: excel vba csv

我是VBA的初学者,必须编写执行以下操作的代码:

1-检索文件夹中的所有csv文件

2-将文件名放在新工作表的第一行。

3-复制csv文件中的所有列标题(第一行)

4-将它们粘贴到新工作表中每个文件名下的一列中。

我知道我需要使用范围,但我很困惑如何使用它。

这是我为获取csv文件所做的工作。我将行复制到列中时遇到问题:

Dim CSVPath
Dim FS
Dim file
Dim wkb As Excel.Workbook
Dim ResultsSheet As Worksheet
Dim RowPtr As Range
Dim CSVUsed As Range

Set ResultsSheet = Sheet1

'Clear the results sheet
ResultsSheet.Cells.Delete

Set FS = CreateObject("Scripting.FileSystemObject")

'The CSV files are stored in a "CSV" subfolder of the folder where
'this workbook is stored.
CSVPath = ThisWorkbook.Path & "\CSV"

If Not FS.FolderExists(CSVPath) Then
    MsgBox "CSV folder does not exist."
    Exit Sub
End If

For Each file In FS.GetFolder(CSVPath).Files
    If Right(file.Name, 3) = "csv" Then 'Only look at files with .csv extension
        Set wkb = Application.Workbooks.Open(file.Path)  

Next

我也知道循环应该是这样的:

FinalRow = Cells(Rows.Count, 1).End(xlUp).Row 

   For x = 2 To FinalRow 

感谢任何帮助

2 个答案:

答案 0 :(得分:1)

尝试类似:

Dim wb1 As Workbook, wb2 As Workbook
Dim colnum
Dim arr1
Dim range2 As Range

colnum = 20
Set wb2 = ThisWorkbook

Set range2 = wb2.Worksheets("Sheet1").Range("A1")   'wherever I want to paste my data to
For Each file In fs.getfolder(CSVPath).file
       If Right(file.Name, 3) = "csv" Then
            Set wb1 = Application.Workbooks.Open(file.Path)
            arr1 = wb1.Worksheets("WHATEVER_ITS_NAME_IS").Range("A1").resize(1, colnum).Value
            rowlen = UBound(arr1, 1) - LBound(arr1, 1) + 1
            collen = UBound(arr1, 2) - LBound(arr1, 2) + 1

            range2.Resize(rowlen, collen).Value = arr1
        End If
Next

有很多方法可以给这只猫上皮。不确定我的代码是否有效但也许这会有所帮助。通常我不喜欢遍历每个细胞。在VBA中,这种循环非常慢。最好一次复制整个阵列。使用Range.Value属性设置/获取Range对象

中的数组数据

答案 1 :(得分:0)

我发现 this article 可以打开并读取文本/csv 文件,然后遍历字符串/变体中的所有项目以添加到 Excel 工作表中。

VBA 代码如下

Sub FillInExcelFromCSV(tempCSV As String, tempXL As String, rowToFill As Integer)

Dim i, counter As Integer
Set tempFile = GetObject(tempCSV)
Set tempXLFile = GetObject(tempXL)
row_number = 1

Open tempCSV For Binary As #1
  Do Until EOF(1)
    Line Input #1, LineFromFile
    LineItems = Split(LineFromFile, ",") 'Gets data from CSV
    counter = 1
    For Each csvVal In LineItems
        Debug.Print (csvVal)
        tempXLFile.Worksheets("Sheet1").Cells(rowToFill, counter).Value = csvVal
        counter = counter + 1
    Next
    row_number = row_number + 1
    Exit Do
  Loop
Close #1
End Sub

Sub vbaTest()
  Call FillInExcelFromCSV("C:\dataFrom.csv","C:\dataTo.xlsx", 5)
End Sub