[英]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.