在 Excel 中,使用 VBA,如何取“路径+文件名+扩展名”并更改扩展名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4466998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:25:37  来源:igfitidea点击:

In Excel, using VBA, how do I take the "path+filename+extension" and change the extension?

excelvba

提问by blunders

Have a program that's dynamically generating an Excel file and a csv. The excel file has VBA code that loads the csv data "on load" and I want to dynamically call that csv by having the csv file have the same filename, but just the different extension. So, based on my understanding this if the xls file was here:

有一个动态生成 Excel 文件和 csv 的程序。excel文件具有“加载时”加载csv数据的VBA代码,我想通过让csv文件具有相同的文件名来动态调用该csv,但只是扩展名不同。所以,根据我的理解,如果 xls 文件在这里:

C:\directory\filename.xls

This VBA code:

这个VBA代码:

Function GetFullName() As String

 GetFullName = ThisWorkbook.FullName 

End Function

Would result in

会导致

GetFullName() = "C:\directory\filename.xls"

So, if that's correct (source of code), how do I replace ".xls" with ".csv" and then insert that value into a file call. Or for example, to keep it simple, the file has VBA that prints a PDF using this code; which would require me to use the GetFullName, and change ".xls" to ".pdf":

因此,如果这是正确的(代码源),我该如何将“.xls”替换为“.csv”,然后将该值插入到文件调用中。或者例如,为了简单起见,该文件具有使用此代码打印 PDF 的 VBA;这需要我使用 GetFullName,并将“.xls”更改为“.pdf”:

Sub PrintPDF()

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\directory\filename.pdf", Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False _

End Sub

Hope the problem is clear, if there's a better solution concept, I'm open to it. If you've got questions, just let me know.

希望问题很清楚,如果有更好的解决方案概念,我愿意接受。如果你有问题,请告诉我。

回答by Fionnuala

Replace could be exactly what you want:

替换可能正是您想要的:

Function GetFullNameCSV() As String

 GetFullNameCSV = Replace(ThisWorkbook.FullName, ".xls",".csv")  

End Function

You can extend this by including the extension you want like so:

您可以通过包含您想要的扩展来扩展它,如下所示:

sFileName = GetNewExt("pdf")

Function GetNewExt(Ext As String) As String

 GetNewExt = Replace(ThisWorkbook.FullName, ".xls","." & Ext)  

End Function