我有以下代码可以查找单元格中的单个单词。为了找到单词,它使用worksheetfunction.find命令在这些单词之间寻找空格。
此过程可以正常进行,直到到达单元格中的最后一个单词为止。由于找不到更多空间,因此将返回错误。我尝试使用application.find命令解决此错误,但是当我这样做时,它会将所有内容都视为错误,并且只需选择单元格中的所有文本即可。
我想知道的是:
Dim a As Double Dim b As Double Dim c As Variant Dim d As Integer Dim e As String Dim f As Double Dim g As Variant Dim h As Variant Dim i As Integer a = 1 f = 2 i = 1 b = Len(Cells(i, 1)) While Cells(i, 1) <> vbNullString While a < b c = vbNullString d = 0 e = vbNullString c = WorksheetFunction.Find(Chr(32), Cells(i, 1), a) If Not IsError(c) Then d = c - a ElseIf IsError(c) Then d = b - a End If e = Mid(Cells(1, 1), a, d) If Left(e, 4) = "true" Then e = "'" & e ElseIf Left(e, 5) = "false" Then e = "'" & e End If If e <> vbNullString Then Worksheets("Words").Cells(f, 1) = WorksheetFunction.Trim(e) f = f + 1 End If If Not IsError(c) Then a = c + 1 Else a = a + d End If Wend i = i + 1 b = Len(Cells(i, 1)) a = 1 Wend
答案 0 :(得分:2)
尝试以下解决方案:将Find
包裹在On Error Resume Next
中,然后,如果返回结果为空字符串,它将符合您的Else
标准,您可以在其中获得最后一个单词单元格:
编辑:经过进一步测试,移至下一行时似乎有点搞砸了……但是以前这样做有用吗?
Dim a As Double
Dim b As Double
Dim c As Variant
Dim d As Integer
Dim e As String
Dim f As Double
Dim g As Variant
Dim h As Variant
Dim i As Integer
a = 1
f = 2
i = 1
b = Len(Cells(i, 1))
While Cells(i, 1) <> vbNullString
While a < b
c = vbNullString
d = 0
e = vbNullString
On Error Resume Next
c = WorksheetFunction.Find(Chr(32), Cells(i, 1), a)
On Error GoTo 0
If c <> "" Then
d = c - a
Else
d = b - a + 1
End If
e = Mid(Cells(1, 1), a, d)
If Left(e, 4) = "true" Then
e = "'" & e
ElseIf Left(e, 5) = "false" Then
e = "'" & e
End If
If e <> vbNullString Then
Worksheets("Words").Cells(f, 1) = WorksheetFunction.Trim(e)
f = f + 1
End If
If c <> "" Then
a = c + 1
Else
a = a + d
End If
Wend
i = i + 1
b = Len(Cells(i, 1))
a = 1
Wend
如果我是从头开始写的,那么这就是我要做的。通过使用Split
,我们可以使用特定的定界符(在本例中为空格字符)分隔单元格的值,然后将所有这些字符写入目标位置:
Option Explicit
Sub Test()
Dim sht As Worksheet
Dim i As Long, j As Long, k As Long
Dim temparr As Variant
Set sht = ActiveSheet
k = 1
For i = 1 To sht.Cells(sht.Rows.Count, 1).End(xlUp).Row
temparr = Split(sht.Cells(i, 1).Value, " ")
For j = 0 To UBound(temparr)
Sheets("Words").Cells(k, 1).Value = temparr(j)
k = k + 1
Next j
Next i
End Sub