浅谈VBA和.NET中文件名信息的处理

在程序中操作文件名是我们经常遇到的事情。使用VBA时有很少的内置功能能帮助你。当使用VB.Net我认为我需要做同样的事情,就像我一直在用VBA做的。直到最近,我发现很多的.Net框架集的实用工具可以使工作更容易。

.Net框架集是使用任何.Net语言编程序的巨大优势之一。相比之下,VBA具有非常少的内置功能。可能你们当中的人和我一样仍然在探寻它的功能,所以我会把我认为.Net中有用的东西介绍到我的博客(Mod the Machine)中来。

在使用VBA的过程中,我写了一些和文件名有关的函数。使用这些我可以提取一个文件名的信息和把它们组织起来产生新的文件名。这些函数如下:

‘ 返回的输入文件名的路径。Public Function FilePath(ByVal fullFilename As String) As String ‘ Extract the path by getting everything up to and ‘ including the last backslash “/”. FilePath = Left$(fullFilename, InStrRev(fullFilename, “/”) – 1) End Function ‘ 返回文件的名称,没有路径。Public Function Filename(ByVal fullFilename As String) As String ‘ Extract the filename by getting everything to ‘ the right of the last backslash. Filename = Right$(fullFilename, Len(fullFilename) – _ InStrRev(fullFilename, “/”)) End Function ‘ 返回输入文件名的基本名称,’ 无路径或扩展名。 Public Function BaseFilename(ByVal fullFilename As String) As String ‘ Extract the filename by getting everttgubg to ‘ the right of the last backslash. Dim temp As String temp = Right$(fullFilename, Len(fullFilename) – _ InStrRev(fullFilename, “/”)) ‘ Get the base filename by getting everything to ‘ the left of the last period “.”. BaseFilename = Left$(temp, InStrRev(temp, “.”) – 1) End Function ‘ 返回的输入文件扩展名。 Public Function FileExtension(ByVal fullFilename As String) As String ‘ Extract the filename by getting everthing to ‘ the right of the last backslash. Dim temp As String temp = Right$(fullFilename, Len(fullFilename) – _ InStrRev(fullFilename, “/”)) ‘ Get the base filename by getting everything to ‘ the right of the last period “.”. FileExtension = Right$(temp, Len(temp) – InStrRev(temp, “.”) + 1) End Function ‘ 测试文件名的函数。 Public Sub TestFileFunctionsVBA() Dim fullFilename As String fullFilename = “C:/Samples/Models/Parts/OilPan/OilPan.ipt” Debug.Print FilePath(fullFilename) Debug.Print Filename(fullFilename) Debug.Print BaseFilename(fullFilename) Debug.Print FileExtension(fullFilename) End Sub

以下是在立即窗口中看到的结果。

C:/Samples/Models/Parts/OilPan OilPan.ipt OilPan .ipt

使用VB.Net将容易得多。.Net框架集支持的IO类具有与文件与文件路径相关功能。IO类提供访问路径的类。如下代码是用VB.Net的功能来做上面的VBA代码所做的相同的事情,但它使用.NET框架集的功能,而不是自定义函数。您将需要导入System.IO Imports命名空间,或直接指定命名空间的完整路径来调用,如GetDirectoryName,就向下面代码显示的:

Imports System.IO ‘ 测试.Net框架集的路径功能。 Public Sub TestFileFunctionsVBNet() Dim fullFilename As String fullFilename = “C:/Samples/Models/Parts/OilPan/OilPan.ipt” Debug.Print(System.IO.Path.GetDirectoryName(fullFilename)) Debug.Print(Path.GetFileName(fullFilename)) Debug.Print(Path.GetFileNameWithoutExtension(fullFilename)) Debug.Print(Path.GetExtension(fullFilename)) End Sub

正如你可以看到的,结果是一样的,但是不必象用VBA一样编写自定义函数。

C:/Samples/Models/Parts/OilPan OilPan.ipt OilPan .ipt

发光并非太阳的专利,你也可以发光

浅谈VBA和.NET中文件名信息的处理

相关文章:

你感兴趣的文章:

标签云: