繁体   English   中英

想要使用excel vba在文件扩展名之前添加后缀

[英]Want to add suffix before file name extension with excel vba

我有以下代码,将列出的后缀和前缀添加到“ B”列中列出的文件名中。 但是问题是,文件扩展名后会添加后缀。 我想在文件名的末尾添加文本。 即如果文件名是test.txt并且我想要的话,则是1test9.txt,但是代码将其重命名为1test.txt9

Sub Add_Pre_Suf()
Dim Pre, Suf As String
Dim r As Range
Pre = Range("C2").Value
Suf = Range("D2").Value
Range("B2").Select
'Range(Selection, Selection.End(xlDown)).Select
Range("B2:B" & Range("B" & Rows.Count).End(xlUp).Row).Select
With Selection

    For Each r In Selection
        r.Value = Pre & r.Value & Suf
    Next

End With
RenameFiles
End Sub

您可以为此使用Scripting.FileSystemObject 只需添加对Microsoft脚本运行时的引用即可:

With New Scripting.FileSystemObject
    Dim filePath As String
    filePath = r.Value
    r.Value = Pre & .GetBaseName(filePath) & Suf & "." & _
              .GetExtensionName(filePath)
End With

您看到此行为的原因是您的B列已具有文件扩展名。 您可以从列中拆分文件扩展名并添加后缀,然后再添加回文件扩展名。 您可以更改代码以执行类似的操作。

With Selection
    For Each r In Selection
        r.Value = Pre & left(r.Value,find(".",r.Value)-1) & Suf & right (r.Value,len(r.Value)-find(".",r.Value)+1)
    Next
End With

编辑:更好的代码将适用于任意数量的字符的扩展名。

这应该做得很好:

Sub Add_Pre_Suf()
        ' 21 Mar 2017

        Dim Pre As String, Suf As String
        Dim Splt() As String
        Dim Ext As String
        Dim R As Long, Rend As Long

        Pre = Range("C2").Value
        Suf = Range("D2").Value

        Rend = Cells(Rows.Count, "B").End(xlUp).Row
        For R = 2 To Rend
            With Cells(R, 2)                     ' 2 = "B"
                If Len(.Value) Then
                    Splt = Split(.Value, ".")
                    Ext = Splt(UBound(Splt))
                    ReDim Preserve Splt(UBound(Splt) - 1)
                    .Value = Pre & " " & Trim(Join(Splt, ".")) & " " & Suf & "." & Ext
                End If
            End With
        Next R

        RenameFiles
    End Sub

调用此代码时请多加注意,因为它没有指定工作表,因此可以在ActiveSheet上使用。 如果不先检查名称确实是我期望的名称,就不会调用“ RenameFiles”过程。

请注意, Range("C2")可以称为Cells(2, 3)

暂无
暂无

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

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