我们说我有以下数组,arr
包含20个子字符串的最大。在此示例中,数组将包含4个子字符串:
arr = {"AAAA: 1234567" , "BBBB: 2345678" , "CCCC: 98765432" , "DDDD: 87654321"}
注意:大写并不重要。
我需要帮助在数组中找到一个子字符串(同样,最多可以包含20个字符串),以 CCCC:
开头,然后将整个字符串分配给它&#39 ; s自己的变量,我们称之为Var1
。
我知道我可以分配Var1 = arr(2)
,但我需要弄清楚如何确定符合我标准的数组中的索引号。
我 真的 欣赏(虽然我会满意的任何方法),正在制作一个独立的功能,例如:
Function ArrayIndex(ArrayInput as Variant, StartsWith as String) as Byte
'Arguments Here
End Function
然后我可以在我的子程序中使用它:
Var1 = arr(ArrayIndex(arr, "CCCC:"))
以下是我当前代码的片段
Sub T_Report
'<Shortcut = Shift+Ctrl+T>
Dim Data as String, DataArray as Variant
With ActiveSession
.Copy 0, 2, 80, 21 'Just a big block of text with multiple lines, copied to clipboard
Data = Clipboard 'Set Data to the clipboard value
DataArray = Split(Data,vbCrLf) 'This is "Data" in an Array, separated by line breaks
'Just checking to see if the Array was successful (it is)
Debug.Print DataArray(0) & vbNL & DataArray(1) & vbNL & DataArray(2) & _
vbNL & DataArray(3) & vbNL & DataArray(4) & vbNL & vbNL
'Misc code here
Dim sF1 as String, sF2 as String, sF3 as String
Dim Rslt1 as String, Rslt2 as String, Rslt3 as String
sF1 = "Field1:"
sF2 = "Field2:"
sF3 = "Field3:"
MsgBox DataArray(0) ' This works fine, giving me first substring
Rslt1 = FindMyString(sF1, DataArray)
' Misc Code
End With
End Sub
但是,当我使用以下函数时,Type Mismatch
行会出现MsgBox arr(0)
错误,尽管它应该在上面的子句中给我DataArray
的第一个子字符串(应该是完全匹配,数组尚未修改).. 但是,当我执行MsgBox DataArray(0)
时,我做获取第一个子字符串。
Private Function FindMyString(strToFind As String, ParamArray arr() As Variant) As String
Dim i As Integer
Dim iLen As Integer
Dim strArr As String
FindMyString = "" ' Returns Blank String if not found
' I get type mismatch here (Doesn't appear Array from sub loaded into this function)
MsgBox arr(0)
iLen = Len(strToFind)
For i = 0 To UBound(arr)
strArr = CStr(arr(i))
If strToFind = Left$(strArr, iLen) Then
FindMyString = strArr
Exit Function
End If
Next i
End Function
答案 0 :(得分:2)
编辑 - 修复您的阵列负载
改变这个(它必须给你一个错误!):
arr = {"AAAA: 1234567" , "BBBB: 2345678" , "CCCC: 98765432" , "DDDD: 87654321"}
至此:
Dim arr As Variant
arr = Split("AAAA: 1234567,BBBB: 2345678,CCCC: 98765432,DDDD: 87654321", ",")
如果要使用函数进行出价,可以使用ParamArray类型传递数据数组。它必须是函数中的最后一个参数
这应该做你想要的:
Private Function FindMyString(strToFind as string, ParamArray arr() As Variant) As String
Dim i As Integer
Dim iLen as Integer
Dim strArr as String
FindMyString = "" ' Returns Blank String if not found '
Debug.Print arr(0)(0) ' Print first element of array
iLen = Len(strToFind)
For i = 0 To UBound(arr(0))
strArr = CStr(arr(0)(i))
If strToFind = Left$(strArr, iLen) Then
FindMyString = strArr
Exit Function
End If
Next i
End Function
在您的示例中,您可以通过以下方式对其进行测试:
Var1 = FindMyString("CCCC:", arr)