我是新在宏观VBA,我正面临一个问题。
我有两个字符串要比较,如果在两个字符串中找到相似的数字,如何得到结果?
字符串1: 1,2,3,4,6,7,8,9,10,11,12,13,19,20
字符串2: 2,3,7,8,9,10,11
经比较后:
结果:2,3,7,8,9,10 11
代码:
If ActiveSheet.Cells(irow + 1, 12).Value = "" Then
'MsgBox "Data not found"
Else
temp = vbNullString
temp = ActiveSheet.Cells(irow + 1, 12).Value
'expanddata() use to expend a sequence of numbers into a display string as below
' 1,2-4,6 -> 1,2,3,4,6
temp = expanddata(temp)
If Worksheets("AI").Cells(irow + 1, 10).Value = temp Then
temp = ConvNum(temp) 'if whole string same then convert back to 1,2-4,6
Else
'the comparision make in here
End If
Worksheets("AI").Cells(irow + 1, 10) = temp
End If
谢谢。
发布于 2016-04-06 03:16:38
自动化powershell将列表打印到文本文件c:\temp\test.txt
Sub Test()
a = "(1,2,3,4,6,7,8,9,10,11,12,13,19,20)"
b = "(2,3,7,8,9,10,11)"
cmd = Shell("powershell.exe """ & a & """ | Where {""" & b & """ -Contains $_} | out-file c:\temp\test.txt", 1)
End Sub
发布于 2016-04-04 07:04:54
请试试下面的代码。
Sub comparestring()
string1 = "1,2,3,4,6,7,8,9,10,11,12,13,19,20"
string2 = "2,3,7,8,9,10,11"
str1 = Split(string1, ",")
str2 = Split(string2, ",")
For i = 0 To UBound(str1)
For j = 0 To UBound(str2)
If str1(i) = str2(j) Then
If matchedcontent <> "" Then
matchedcontent = matchedcontent & "," & str1(i)
Else
matchedcontent = str1(i)
End If
End If
Next j
Next i
Range("A3").Value = matchedcontent
End Sub
将这两个字符串赋值为字符串1和字符串2,如下所示,结果将在单元格A3中打印
string1=Activesheet.Range("A1").Value
string2=Activesheet.Range("A2").Value
发布于 2016-04-04 07:11:37
尝尝这个
Option Explicit
Function CompareStrings(string1 As String, string2 As String) As String
Dim s As Variant
For Each s In Split(string1, ",")
If "," & string2 & "," Like "*," & s & ",*" Then CompareStrings = CompareStrings & s & ","
Next s
CompareStrings = Left(CompareStrings, Len(CompareStrings) - 1)
End Function
可以按以下方式调用
Sub main()
Dim string1 As String, string2 As String, stringRes As String
string1 = "1,2,3,4,6,7,8,9,10,11,12,13,19,20"
string2 = "2,3,7,8,9,10,11"
stringRes = CompareStrings(string1, string2)
MsgBox stringRes
End Sub
https://stackoverflow.com/questions/36393582
复制相似问题