通过VBA将Excel表格写入CSV

时间:2016-10-07 16:24:07

标签: excel vba macros

我有一张带有固定表的excel电子表格。我想创建一个按钮,按下该按钮时,会将该表导出为CSV文件。

我创建了一个按钮并实现了以下代码;但是当我按下按钮时,文件只创建了逗号(没有添加来自单元格的数据)。我错过了什么?我是VBA的新手 - 谢谢。

 Sub CommandButton21_Click()

Dim FilePath As String
Dim CellData As String

CellData = ""

FilePath = Application.DefaultFilePath & "\Table.txt"

Open FilePath For Output As #1


For i = 30 To 34

For j = 3 To 7

CellData = CellData + Trim(ActiveCell(i, j).Value) + ","

Next j
Write #1, CellData

CellData = ""

Next i

Close #1



End Sub

3 个答案:

答案 0 :(得分:1)

Excel会将整个工作表保存为.csv文件。您不需要单独保存单元格。

使用此代码

Sub CSVfile()
    ActiveWorkbook.SaveAs Filename:="C:\Users\AlexBor\Documents\my_excel_sheet.csv",    _
    FileFormat:=xlCSV, CreateBackup:=False
End Sub

它将保存所有非空单元格,保留表格格式。当然,您可以选择其他文件格式.txt和tab分隔符,例如。

答案 1 :(得分:0)

Option Explicit

Sub CSV_toCSV(ByVal tablename As String)
    Dim theTable As ListObject

    Set theTable = ThisWorkbook.ActiveSheet.ListObjects(tablename)
    toCSV_header theTable, ",", """", """"""
    toCSV_data theTable, ", ", """", """"""
End Sub

Sub CSV_toDBInserts(ByVal tablename As String)
    Dim theTable As ListObject

    Set theTable = ThisWorkbook.ActiveSheet.ListObjects(tablename)
    toCSV_header theTable, ", ", "", "", "INSERT INTO " & theTable.Name & " (", ") VALUES"
    toCSV_data theTable, ", ", "'", "''", "(", "),", ");"
End Sub

Private Sub toCSV_header(ByRef table As ListObject, ByVal delimiter As String, ByVal quote As String, ByVal quoteWith As String, Optional ByVal prefix As String = "", Optional ByVal postfix As String = "")
    Dim theTable As ListObject
    Dim line As String
    Dim curVal As String
    Dim c  As Integer
    Dim first As Boolean
    first = True

    Set theTable = ThisWorkbook.ActiveSheet.ListObjects("thetable")

    line = prefix
    For c = 1 To theTable.ListColumns.Count
        If first Then
            first = False
        Else
            line = line & delimiter
        End If

        curVal = theTable.HeaderRowRange.Cells(1, c).Value
        If Not quote = "" Then
            curVal = Replace(curVal, quote, quoteWith)
        End If
        line = line & quote & curVal & quote
    Next c
    line = line & postfix

Debug.Print line
End Sub

Private Sub toCSV_data(ByRef table As ListObject, ByVal delimiter As String, ByVal quote As String, ByVal quoteWith As String, Optional ByVal prefix As String = "", Optional ByVal postfix As String = "", Optional ByVal globalPostfix As String = "")
    Dim theTable As ListObject
    Dim line As String
    Dim curVal As String
    Dim r, c, h  As Integer
    Dim first As Boolean
    first = True

    Set theTable = ThisWorkbook.ActiveSheet.ListObjects("thetable")

    'Change the path and file name accordingly
    'Open "/Users/hoffmd9/tmp" For Output As #1

    For r = 1 To theTable.DataBodyRange.Rows.Count
        line = prefix
        For c = 1 To theTable.DataBodyRange.Columns.Count
            If first Then
                first = False
            Else
                line = line & delimiter
            End If

            curVal = theTable.DataBodyRange.Cells(r, c).Value
            If Not quote = "" Then
                curVal = Replace(curVal, quote, quoteWith)
            End If
            line = line & quote & curVal & quote

        Next c
        If r = theTable.ListRows.Count Then
            line = line & globalPostfix
        Else
            line = line & postfix
        End If
        first = True
Debug.Print line
    Next r

    'Change the path and file name accordingly
    'Open "/Users/hoffmd9/tmp" For Output As #1
    'Write #1, CStr(Cells(i, j).Value);
    'Close #1

End Sub

答案 2 :(得分:0)

const myPromiseAllSettled = (promises) => new Promise((resolve, reject) => {
  const results = []
  const settle = (result) => {
    results.push(result)
    if (results.length === promises.length) {
      (results.every(value => value) ? resolve : reject)(promises)
    }
  }
  promises.forEach(promise => {
    promise
      .then(() => settle(true))
      .catch(() => settle(false))
  })
})
  1. 将表格的全部内容存储到一个二维数组中——tblArr
  2. 对于每一行 – 将数据提取到一维数组 rowArr
  3. 将一维数组的所有数据以逗号为分隔符,并存入一个变量——csvVal
  4. 在 csv 文件(已创建)中打印此逗号分隔数据
  5. 对表的每一行重复这个过程 - For 循环用于这样做