比较两个dynamicstring数组

我正在寻找一些指导和经验。 我有一个创build两个string的VBA模块。 见下文。 我想使用一个数组来比较两个stings,并将成功的匹配或“不匹配”写入第三个数组或直接写入工作表。 第二部分是Arr2与Arr1的“百分比”匹配。 所以下面的例子是88%。

> Arr1 result > 726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X > Arr2 result > 726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X 

任何build议将是伟大的。

尝试这个:

 Sub Test() Dim str1 As String, str2 As String Dim arr, i As Long, cnt As Long str1 = "726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X" str2 = "726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X" For i = LBound(Split(str1, ",")) To UBound(Split(str1, ",")) If Not IsArray(arr) Then arr = Array(IIf(Split(str1, ",")(i) = _ Split(str2, ",")(i), "Match", "NoMatch")) Else ReDim Preserve arr(UBound(arr) + 1) arr(UBound(arr)) = IIf(Split(str1, ",")(i) = _ Split(str2, ",")(i), "Match", "NoMatch") End If Next '~~> Check the array For i = LBound(arr) To UBound(arr) Debug.Print arr(i) If arr(i) = "Match" Then cnt = cnt + 1 Next '~~> output the percentage MsgBox Format(cnt / (UBound(arr) + 1), "0.00%") End Sub 

这是使用简单for循环完成任务的一种方法。

 Sub compareStrings() Dim str1 As String Dim str2 As String str1 = "726741,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X" str2 = "726742,439037,X41033X,X0254XX,X47083X,X0252XX,X50047X,XH5815X" Dim Arr1 As Variant Dim Arr2 As Variant Dim ArrResults As Variant Arr1 = Split(str1, ",") Arr2 = Split(str2, ",") Dim countMatches As Integer countMatches = 0 ReDim ArrResults(UBound(Arr1)) For i = LBound(Arr1) To UBound(Arr1) If Arr1(i) = Arr2(i) Then ArrResults(i) = "Matches" countMatches = countMatches + 1 Else ArrResults(i) = "No Match" End If Next i 'Print out the results array in debug window For Each entry In ArrResults Debug.Print entry Next entry Dim ratio As Double ratio = countMatches / (UBound(Arr1) + 1) MsgBox (ratio * 100 & "%") End Sub 

消息框将显示这个:

在这里输入图像说明


立即窗口将显示结果数组值如下:

在这里输入图像说明