简体   繁体   English

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

[英]Export Excel data to CSV file using the Excel file name

I am using a solution provided by the user The_Barman for exporting specific cells from an Excel document to a CSV document: 我正在使用用户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

I am wondering if it would be possible and how I would go about having the CSV file name reference the originating Excel document's filename that the VBA script was run on, rather than having to manually input it into the code each time. 我想知道是否有可能,以及如何使CSV文件名引用运行VBA脚本的原始Excel文档的文件名,而不是每次都要手动将其输入到代码中。

ie have "C:\\temp\\Filename.csv" save as "C:\\temp\\ExcelSpreadsheet.csv" without manually inputting the "ExcelSpreadsheet" filename each time it is run: 例如,将“ 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

Thank you for any assistance you may provide 多谢您提供的协助

Try this: 尝试这个:

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

But you do know this means you need to add the VBA code to each file you run it on? 但是您知道这意味着您需要将VBA代码添加到运行它的每个文件中吗?
You could make it an add-in and access the VBA code "externally" and that way you don't need to copy paste the code to each file. 您可以将其作为外接程序并“外部”访问VBA代码,这样就无需将代码复制粘贴到每个文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM