使用Excel文件名将Excel数据导出到CSV文件

时间:2016-11-09 12:36:56

标签: excel vba excel-vba csv

我正在使用用户The_Barman提供的解决方案,用于将特定单元格从Excel文档导出到CSV文档:

Sub WriteCSVFile()

Dim My_filenumber As Integer
Dim logSTR As String

My_filenumber = FreeFile

logSTR = logSTR & Cells(18, "C").Value & " , "
logSTR = logSTR & Cells(19, "C").Value & " , "
logSTR = logSTR & Cells(20, "C").Value & " , "
logSTR = logSTR & Cells(21, "C").Value & " , "
logSTR = logSTR & Cells(27, "C").Value & " , "
logSTR = logSTR & Cells(28, "C").Value & " , "
logSTR = logSTR & Cells(29, "C").Value & " , "
logSTR = logSTR & Cells(30, "C").Value & " , "
logSTR = logSTR & Cells(31, "C").Value & " , "
logSTR = logSTR & Cells(32, "C").Value & " , "

Open "C:\temp\Filename.csv" For Append As #My_filenumber
    Print #My_filenumber, logSTR
Close #My_filenumber

End Sub

我想知道是否可能以及如何让CSV文件名引用运行VBA脚本的原始Excel文档的文件名,而不是每次都必须手动将其输入到代码中。 / p>

即。将“C:\ temp \ Filename.csv”保存为“C:\ temp \ ExcelSpreadsheet.csv”,而不是每次运行时都手动输入“ExcelSpreadsheet”文件名:

Open "C:\temp\Filename.csv" For Append As #My_filenumber Print #My_filenumber, logSTR Close #My_filenumber

感谢您提供的任何帮助

1 个答案:

答案 0 :(得分:0)

试试这个:

Sub WriteCSVFile()

    Dim My_filenumber As Integer
    Dim logSTR As String

    My_filenumber = FreeFile

    logSTR = logSTR & Cells(18, "C").Value & " , "
    logSTR = logSTR & Cells(19, "C").Value & " , "
    logSTR = logSTR & Cells(20, "C").Value & " , "
    logSTR = logSTR & Cells(21, "C").Value & " , "
    logSTR = logSTR & Cells(27, "C").Value & " , "
    logSTR = logSTR & Cells(28, "C").Value & " , "
    logSTR = logSTR & Cells(29, "C").Value & " , "
    logSTR = logSTR & Cells(30, "C").Value & " , "
    logSTR = logSTR & Cells(31, "C").Value & " , "
    logSTR = logSTR & Cells(32, "C").Value & " , "

    Open "C:\temp\" & ThisWorkbook.Name & ".csv" For Append As #My_filenumber
          Print #My_filenumber, logSTR
    Close #My_filenumber

End Sub

但是你知道这意味着你需要将VBA代码添加到你运行它的每个文件中吗? 您可以将其设为加载项并访问VBA代码"外部"这样你就不需要将代码粘贴到每个文件中。