繁体   English   中英

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

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

我正在使用用户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文档的文件名,而不是每次都要手动将其输入到代码中。

例如,将“ 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

多谢您提供的协助

尝试这个:

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代码,这样就无需将代码复制粘贴到每个文件中。

暂无
暂无

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

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