0

所以我在这里找到了一个很好的答案,展示了如何获取括号之间的值或字符串(获取括号之间的值)该代码运行良好,但是当涉及方括号时,如以下代码所示,它给了我一个错误我一整天都在努力解决这个问题。我似乎无法弄清楚我的问题是什么。我收到的错误通知是:“运行时错误'5':无效的过程调用或参数”

For i = 6 To Worksheets(FileName).UsedRange.Columns.Count 

    kursName = Worksheets(FileName).Cells(1, i).Value

    klammerAuf = InStr(kursName, "[")
    klammerZu = InStr(kursName, "]")
    Cells(3, i) = Mid(kursName, klammerAuf + 1, klammerZu - klammerAuf - 1)
Next i
4

2 回答 2

0

尝试这个:

Function GetTextWithinBrackets(kursName As String, left As String, right As String)
    klammerAuf = InStr(kursName, left)
    klammerZu = InStr(klammerAuf + 1, kursName, right) ' start searching for the closing bracket after the opening one
    If klammerAuf * klammerZu Then ' check if both brackets were found
        GetTextWithinBrackets = Mid(kursName, klammerAuf + 1, klammerZu - klammerAuf - 1)
    Else
        GetTextWithinBrackets = "No " & left & " or " & right & " in the text"
    End If
End Function

Sub test()
    Debug.Print GetTextWithinBrackets("jkdsf]]]klsjc[=the text within brackets=]asd[[aw]]sd", "[", "]")
    Debug.Print GetTextWithinBrackets("872639281(=the text within brackets=)slsx(sladmlsa)", "(", ")")
    Debug.Print GetTextWithinBrackets("872639281=the text within brackets=]slsx(sladmlsa)", "[", "]")
End Sub

输出:

=the text within brackets=
=the text within brackets=
No [ or ] in the text
于 2022-02-20T17:33:52.263 回答
0

好吧,我可能已经找到了解决方案。所选单元格没有带方括号的值。问题是我没有对错误进行任何处理。我会把这个问题留给将来可能遇到同样错误的其他人。伙计,我觉得自己很笨。我会接受任何错误处理的建议。

于 2022-02-20T17:30:39.950 回答