简体   繁体   English

VBA Excel 函数 - 无效的限定符

[英]VBA Excel Function - Invalid Qualifier

Building a VBA excel function that compares each position of 2 string arguments to see if they are equal then return the distance between them.构建一个 VBA excel 函数,比较 2 个字符串参数的每个位置,看看它们是否相等,然后返回它们之间的距离。

Ex.前任。 Given "the" and "dog" should return 3. Given "cat" and "hat" should return 1.给定“the”和“dog”应该返回3。给定“cat”和“hat”应该返回1。

Currently using the below code the function fails compile with Invalid Qualifier - on the line "str1.Chars(i)", the help page explains that this would mean that str1 is out of scope for this code block, and I was unsure how that was possible as other examples I have searched are able to use their arguments in the function.当前使用以下代码,该函数无法使用无效限定符编译 - 在“str1.Chars(i)”行上,帮助页面解释说这意味着 str1 超出了此代码块的范围,我不确定这是怎么回事是可能的,因为我搜索过的其他示例能够在函数中使用它们的参数。

Function hamming_dist(str1 As String, str2 As String) As Integer

hamming_dist = 0
    
For i = 0 To Len(str1)
    If str1.Chars(i) = str2.Chars(i) Then
        hamming_dist = hamming_dist + 1
    End If
Next
    
End Function

UPDATED code:更新代码:

Function hamming_dist(str1 As String, str2 As String) As Integer

hamming_dist = 0
    
For i = 1 To Len(str1)
    If Mid(str1, i, 1) <> Mid(str2, i, 1) Then
        hamming_dist = hamming_dist + 1
    End If
Next
    
End Function

As Warcupine's comment also says, you were looking at Visual Basic .NET documentation.正如 Warcupine 的评论所说,您正在查看 Visual Basic .NET 文档。 In VBA, String is not of type object, it does not have any methods/properties.在 VBA 中,String 不是对象类型,它没有任何方法/属性。 When you Google, always add "VBA" and check if the page is really about that.当您使用 Google 时,请始终添加“VBA”并检查该页面是否真的与此相关。

you are looking for mid() function, that cuts a char from the string.您正在寻找 mid() 函数,它从字符串中剪切一个字符。

actualy, your code calculates the same chars and not the different ones.实际上,您的代码计算相同的字符而不是不同的字符。

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

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