将csv转换为xslx并使用VBA将列添加到前面,其中包含文件名值

时间:2015-05-06 14:22:58

标签: excel vba excel-vba

我正在尝试将csv文件转换为excel文件,并在前面添加列, 使用新添加的列我想用该工作表的文件名填充它,直到该工作表中存在数据的最后一行,我正在使用的代码是

Sub CSVtoXlsx()

 Dim CSVfolder As String
 Dim XlsFolder As String
 Dim fname As String
 Dim wBook As Workbook

 lastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
 strAddress2 = "A3:A" & lastRow
 wbName = ActiveWorkbook.Name

 CSVfolder = "C:\csvfolder\"
 XlsFolder = "C:\xlsFolder\"

 fname = Dir(CSVfolder & "*.csv")

 Do While fname <> ""
    Set wBook = Workbooks.Open(CSVfolder & fname, Format:=6, Delimiter:=",")
    wBook.SaveAs XlsFolder & Replace(fname, ".csv", ""), xlWorkbookDefault
    ActiveCell.EntireColumn.Insert
    ActiveWorkbook.Save
    Range(strAddress2).Value = Left(wbName, InStrRev(wbName, ".") - 1)
    wBook.Close False
 fname = Dir
Loop

End Sub

此代码成功将csv文件转换为xslx格式,并在其前面添加了一个新列,但它没有用文件名填充新添加的列。

1 个答案:

答案 0 :(得分:0)

一旦打开新工作簿,它就会成为ActiveWorkbook。保存它,然后设置第一列,然后关闭它而不再保存它。