簡體   English   中英

Excel VBA - 按名稱調用應用程序功能(左,右)

[英]Excel VBA - Call application function (left, right) by name

我希望能夠使用字符串變量調用應用程序函數,如left()和right()。

原因是我當前的代碼工作正常,但有多個left()和right()實例,每次運行時都需要更改。 我希望每次只能改變一次(“全球”)。

谷歌搜索后,我嘗試了CallByNameApplication.Run 它們似乎只適用於自定義類/宏。 這是真的? 還有什么我應該研究的嗎? 我不需要特定的代碼,謝謝!

如果您想要LeftRight您可以構建一個自定義函數。

Option Explicit

Sub Test()

    Debug.Print LeftRight("L", "StackOverflow", 5)
    Debug.Print LeftRight("R", "StackOverflow", 8)

End Sub

Function LeftRight(sWhich As String, sValue As String, iLength As Integer) As String

    Select Case sWhich

        Case "L": LeftRight = Left(sValue, iLength)
        Case "R": LeftRight = Right(sValue, iLength)

    End Select

End Function

您只需根據需要使用“L”或“R”。 改變它一次並且每次都傳遞給sWhich 您甚至可以使用單元格引用並在運行代碼之前更新單元格。

結果

溢出

最簡單的方法是用通用函數替換所有的LeftRight調用,例如代替

x = Left("abc", 2)

x = LeftOrRight("abc", 2)

然后有一個功能

Function LeftOrRight(str As Variant, len As Long) As Variant
    'Uncomment this line for Left
    LeftOrRight = Left(str, len)
    'Uncomment this line for Right
    LeftOrRight = Right(str, len)
End Function

然后您可以根據需要更改一個功能。

您也可以使用SWITCH來實現Scott的想法(如果字符串長度無效,則不進行錯誤處理):

Sub Test()
    Debug.Print LeftRight("L", "StackOverflow", 5)
    Debug.Print LeftRight("R", "StackOverflow", 8)
End Sub

Function LeftRight(sWhich As String, sValue As String, iLength As Integer) As String
     LeftRight = Switch(sWhich = "L", Left$(sValue, iLength), sWhich = "R", Right$(sValue, iLength))
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM