VBA将CSV文件导入OjbExcel

时间:2015-09-07 14:19:09

标签: vba csv scripting

我一直试图通过在VBA中提供.Csv文件来生成excel。 我们正在使用一个使用vba的内部业务程序,所以我必须引用objExcel。

此:

Function load_csv()
Dim objExcel
Dim objWorkbook
Dim baseSheet
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.workbooks.Add()
Set baseSheet = objWorkbook.worksheets(1)


With objExcel.ThisWorkbook.Sheets("Data").QueryTables.Add(Connection:="TEXT;FILENAME.csv", Destination:=Range("$A$1"))
    .Name = "CAPTURE"
    .fieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False

End With
objExcel.ActiveWorkbook.SaveAs

Set objExcel = Nothing
Set objWorkbook = Nothing
Set baseSheet = Nothing
End Function

给我一​​个应用程序定义或对象定义的错误。

我做错了什么?

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

这将更加接近。您仍然需要定义所有Excel常量,例如xlInsertDeleteCells。您可以在Excel中的VB编辑器对象浏览器(按F2)中找到它们的值。您还应该提供CSV文件的完整路径。

Function load_csv()

Const xlInsertDeleteCells = 1
Const xlDelimited = 1
Const xlTextQualifierDoubleQuote = 1

Dim objExcel As Object
Dim objWorkbook As Object
Dim baseSheet As Object
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.workbooks.Add()
Set baseSheet = objWorkbook.worksheets(1)


With baseSheet.QueryTables.Add(Connection:="TEXT;FILENAME.csv", _
                              Destination:=baseSheet.Range("$A$1"))
    .Name = "CAPTURE"
    .fieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False

End With

objWorkbook.SaveAs "C:\Temp.xlsx" '<<<< needs a path
objWorkbook.Close False

Set objExcel = Nothing


End Function