简体   繁体   English

excel vba - 将 iferror/find 公式转换为 vba

[英]excel vba - convert iferror/find formula to vba

I have the following excel formula我有以下 excel 公式

IFERROR(MID(B7;FIND(" ";B7)+1;1);"")

I want to convert this now to VBA, but I have trouble integrating the Find function here.我现在想将其转换为 VBA,但我无法在此处集成 Find function。 This is what I have so far这是我到目前为止所拥有的

IfError(Mid(Sheets("MySheet").Cells(x, 7),Sheets("MySheet").Cells(x, 7).Find " " + 1, 1), "")

But that's clearly not correct.但这显然是不正确的。 Can somebody help me with this?有人可以帮我吗?

Something like so, called like get_first_char_after_space("testing xys")像这样的东西,叫做get_first_char_after_space("testing xys")

Function get_first_char_after_space(strInput As String) As String

If InStr(1, strInput, Chr(32)) > 0 Then
    get_first_char_after_space = Left(Split(strInput, Chr(32))(1), 1)
Else
    get_first_char_after_space = vbNullString
End If

End Function

You can find the solution for IFERROR at the following SO question: https://stackoverflow.com/a/29390944/6908282 .您可以在以下 SO 问题中找到 IFERROR 的解决方案: https://stackoverflow.com/a/29390944/6908282

And VBA has a Range.Find menthod which you can use to replaicate FIND formula.并且 VBA 有一个 Range.Find 方法,您可以使用它来复制 FIND 公式。 Documentation link: https://docs.microsoft.com/en-us/office/vba/api/excel.range.find文档链接: https://docs.microsoft.com/en-us/office/vba/api/excel.range.find

Here is a UDF to do the job of your worksheet function.这是完成工作表 function 工作的 UDF。 As you see, an error can be avoided in VBA.如您所见,在 VBA 中可以避免错误。 I presume that the entire function could be compressed into one line but whatever benefit that might entail would come at the cost of readability and possibly stability.我认为整个 function 可以压缩成一行,但可能带来的任何好处都会以可读性和可能的稳定性为代价。 As it is, the code is very robust.事实上,代码非常健壮。 It easily transplants into a bigger project as, no doubt, is your intention.它很容易移植到更大的项目中,毫无疑问,这是您的意图。

Function NextChar(Cell As Range) As String
    ' IFERROR(MID(B7;FIND(" ";B7)+1;1);"")

    Dim Txt As String
    Dim n As Integer

    Txt = Cell.Value
    n = InStr(Txt, " ")
    If n Then NextChar = Mid(Txt, n + 1, 1)
End Function

If called from the worksheet the function would be =NextChar(B7) .如果从工作表中调用 function 将是=NextChar(B7) Called from code it would be Debug.Print NextChar(Sheet1.Cells(7, 2))从代码调用它将是Debug.Print NextChar(Sheet1.Cells(7, 2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM