VBA用于斜杠文件名之间的单词

时间:2017-02-06 16:37:57

标签: excel vba excel-vba

我构建了一个基于名称列表保存工作簿的宏。 我收到了一个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

我让它适用于第一种情况,那里只有一个/但无法想出休息。

 InStr(Value, "/") > 0 Then
 filename = Right(Value, (Len(Value) - InStr(Value, "/")))
 Else
 filename = Value
 End If

是我到目前为止所得到的。

由于

5 个答案:

答案 0 :(得分:7)

您可以拆分,修剪和加入:

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

答案 1 :(得分:3)

另一种解决方案,这次使用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

输出应符合预期。

答案 2 :(得分:2)

使用您已有的代码,您可以使用VBA替换功能来替换" /"用" - "

filename = Replace(filename, "/", "-")

答案 3 :(得分:1)

您需要使用REPLACE

https://www.techonthenet.com/excel/formulas/replace_vba.php

示例:

Dim oldString as String
Dim newString as String
newString=Replace(oldString,"/","_")

答案 4 :(得分:0)

你可以使用

filename = Join(Split(Replace(Replace(Value, " ", ""), "team/", ""), "/"), "-")