VBA为斜杠之间的文件名称
我build立了一个基于名称列表保存工作簿的macros。 我得到一个saveAs错误,因为一些新的列表项,有/不允许在一个文件名。
我需要一些帮助来编写这样的代码:请注意,球队,名称,联赛和杯子的列表每一行都会改变。
list item: team/ league what I want: league list item: team / league / cup What I want: league-cup List item; team / league / cup / score what I want: league-cup-score
我有它的第一个场景,只有一个/但不能找出rest的工作。
InStr(Value, "/") > 0 Then filename = Right(Value, (Len(Value) - InStr(Value, "/"))) Else filename = Value End If
是我到目前为止。
谢谢
你可以拆分,修剪和join:
Function MakeFileName(s As String) As String Dim v As Variant, w As Variant Dim i As Long, n As Long v = Split(s, "/") n = UBound(v) ReDim w(1 To n) For i = 1 To n w(i) = Trim(v(i)) Next i MakeFileName = Join(w, "-") End Function
例如:
Sub test() Debug.Print MakeFileName("team/ league") Debug.Print MakeFileName("team / league / cup") Debug.Print MakeFileName("team / league / cup / score") End Sub
输出:
league league-cup league-cup-score
又一个解决scheme,这次使用InStr
。 编辑来处理没有联赛的地方。
Sub Example() Dim str1 As String: str1 = "list item: team/ league" Dim str2 As String: str2 = "list item: team / league / cup " Dim str3 As String: str3 = "List item; team / league / cup / score" Debug.Print getTeamText(str1) Debug.Print getTeamText(str2) Debug.Print getTeamText(str3) End Sub Function getTeamText(ByVal StringIn As String) As String Dim strPos As Long Dim lookFor As String: lookFor = "league" strPos = InStr(1, LCase(StringIn), lookFor) If strPos > 0 Then getTeamText = Replace(Replace(Mid(StringIn, strPos, (Len(StringIn) - strPos) + 1), " ", ""), "/", "-") Else getTeamText = "Could not find match" End If End Function
产出应如预期。
使用已有的代码,可以使用VBAreplace函数将“/”replace为“ – ”
filename = Replace(filename, "/", "-")
您需要使用REPLACE
https://www.techonthenet.com/excel/formulas/replace_vba.php
例:
Dim oldString as String Dim newString as String newString=Replace(oldString,"/","_")
你可以使用
filename = Join(Split(Replace(Replace(Value, " ", ""), "team/", ""), "/"), "-")