首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用FileSystemObject读写csv文件

使用FileSystemObject读写csv文件
EN

Stack Overflow用户
提问于 2012-02-25 15:32:10
回答 2查看 41.4K关注 0票数 3

是否可以在VBA中使用FileSystemObject读写csv文件?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-25 17:31:41

当然是这样。

基本语法,如

代码语言:javascript
复制
    Set objFSO = CreateObject("scripting.filesystemobject")
    'create a csv file
    Set objTF = objFSO.createtextfile("C:\test\myfile.csv", True, False)
    'open an existing csv file with writing ability
    Set objTF = objFSO.OpenTextFile("C:\test\myfile.csv", 8) 

将使用FSO创建/打开一个CSV

然后,可以通过对其进行写入来修改CSV

虽然这是一个Excel示例,但您可以使用相同的技术从Outlook、Access、Word等中写入记录

代码语言:javascript
复制
Const sFilePath = "C:\test\myfile.csv"
Const strDelim = ","
Sub CreateCSV_FSO()
    Dim objFSO
    Dim objTF
    Dim ws As Worksheet
    Dim lRow As Long
    Dim lCol As Long
    Dim strTmp As String
    Dim lFnum As Long

    Set objFSO = CreateObject("scripting.filesystemobject")
    Set objTF = objFSO.createtextfile(sFilePath, True, False)

    For Each ws In ActiveWorkbook.Worksheets
        'test that sheet has been used
        Set rng1 = ws.UsedRange
        If Not rng1 Is Nothing Then
            'only multi-cell ranges can be written to a 2D array
            If rng1.Cells.Count > 1 Then
                X = ws.UsedRange.Value2
                'The code TRANSPOSES COLUMNS AND ROWS by writing strings column by column
                For lCol = 1 To UBound(X, 2)
                    'write initial value outside the loop
                    strTmp = IIf(InStr(X(1, lCol), strDelim) > 0, """" & X(1, lCol) & """", X(1, lCol))
                    For lRow = 2 To UBound(X, 1)
                        'concatenate long string & (short string with short string)
                        strTmp = strTmp & (strDelim & IIf(InStr(X(lRow, lCol), strDelim) > 0, """" & X(lRow, lCol) & """", X(lRow, lCol)))
                    Next lRow
                    'write each line to CSV
                    objTF.writeline strTmp
                Next lCol
            Else
                objTF.writeline IIf(InStr(ws.UsedRange.Value, strDelim) > 0, """" & ws.UsedRange.Value & """", ws.UsedRange.Value)
            End If
        End If
    Next ws

    objTF.Close
    Set objFSO = Nothing
    MsgBox "Done!", vbOKOnly

End Sub
票数 10
EN

Stack Overflow用户

发布于 2012-02-25 15:44:59

这似乎是可能的。

FileSystemObject ( FSO )提供了访问Windows文件系统的应用程序接口,提供对文件、驱动器、文本流等的访问。FSO嵌入在微软脚本运行时中,可供独立应用程序(例如,使用Visual Basic编码)、使用VBScript或JScript的网页设计者以及使用Visual Basic Applications的Microsoft Office应用程序的用户使用。

一些参考资料:

Using The FileSystemObject With VB and VBA

How do I use FileSystemObject in VBA?

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9442215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档