我有两列我在比较两个文本的文本。 A栏包含文字' Hello 2005 A LW Allocate'并且列B具有文本' A LW' 。我想在A列中拆分文本,以便C列应该具有' Hello 2005 Allocate'和D应该有一个LW'。 B列中的值可以是值{A,A LW,I,J}等特定列表中的值,并且我希望将相同的文本与列A的文本进行匹配并将其拆分。如果有人可以提供帮助,我将非常感激。现在,我有一个看起来像这样的代码:
`Sub Testing()
Dim DataRange As Range, CheckRange As Range, aCell As Range, bCell As Range
Dim rightStrng As String
Dim i As Long
Set ws = Worksheets("Sheet 1")
Set CheckRange = ws.Range("C2,C35000") - Column which has data
Set DataRange = ws.Range("F2,F34") - Column to which I am comparing data
With Worksheets("Sheet 1")
For Each aCell In CheckRange.Rows
Set bCell = DataRange.Find(What:=aCell, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Set strng = Split(bCell)
Set rightStrng = ""
i = UBound(strng)
rightStrng = Application.WorksheetFunction.Trim(rightStrng)
Set bCell.Offset(, 2) = rightStrng
Set bCell.Offset(, 1) = Left(aCell.Value, IIf(rightStrng <> "", InStrRev(bCell.Value, rightStrng) - 2, Len(bCell.Value)))
Next aCell
End Sub`
答案 0 :(得分:0)
不可否认,这个答案仍然是一点点: https://www.youtube.com/watch?v=2ZO1jauV31U
但我觉得尽管有类似的原始帖子,但仍然给予了诚实的努力。
方法:
看起来你正在尝试进行一些字符串解析,返回字符串中空格的位置,然后使用Left
返回左半部Mid
返回中间位置,{{ 1}}返回正确的部分。相反,我可能会尝试迭代可能的条目列表,如果找到它们,用Right
替换它们并打印我在B列中找到的条目
Instr([开始],[String1],[String2],[比较]:
如果找不到字符串,vbNullString
函数将返回Instr
中找到的String2
的位置或零。 String1
是字符串中的起始位置(通常为1开头)。 Start
是唯一真正的可选参数,指定如何比较字符串。
Compare
替换
Debug.Print Instr(1, "abcd", "b") '<-- prints 2 in your immediate window
函数将返回Replace(Expression, Find, Replace)
字符串,其中Expression
字符串的实例已替换为Find
字符串。
Replace
您的申请
一些伪代码供您考虑:
Debug.Print Replace("abcdefg", "abc", "ABC") '<-- Prints "ABCdefg" in the immediate window.
代码中的错误
我怀疑您收到的错误信息是:
Dim searchVals(3) as String
searchVals(0) = " A "
searchVals(1) = " A LW "
searchVals(2) = " I "
searchVals(3) = " J " '<-- surrounded with spaces so we don't find all Js
'...some code you already wrote...
For Each myCell in myColumn
For i = 0 to 3
'For each search value I expect to find...
'If this search value is in there...
If InStr(1, myCell.Value, searchVals(i)) <> 0 Then
'I found my string! Replace the searchVal with a null string (i.e. remove it)
myCell.Offset(,1) = Replace(myCell.Value, searchVals(i), vbNullString)
'Print the string I found two to the Right
myCell.Offset(,2) = searchVals(i)
Exit For '<-- Once I find one, I can stop searching
End If
Next i
Next myCell
{@ 1}}关键字是为VBA中的对象保留的,Set strng = Split(bCell)
返回一个字符串数组。所以这两行:
Set
应该是:
Split
对于新手来说,这通常需要记住,但有关Set strng = Split(bCell)
Set rightStrng = ""
关键字的作用的更多技术内容:What does the keyword Set actually do in VBA?