2013-01-10 37 views
0

我想在我的文本字段中基於空格字符的子字符串,但是我無法成功完成。Microsoft Acess中的掃描功能?

我的領域有兩個,但有時三個單詞都分隔y空間。我希望能夠通過匹配空間來拉出第二或第三個單詞。這個詞是可變長度的。

我試過這樣的事情,但沒有成功。

select mid([genus],InStr([genus]," ")+1) AS species from <tablename>; 

有什麼建議嗎? 謝謝。

+1

那麼你想要哪個,第二個或第三個單詞?你只想要最後一個字嗎?你想要第二個單詞的列和第三個單詞的不同列嗎?你是否想要一個使用隨機函數的列來返回第二個或第三個單詞? – mwolfe02

回答

2

對於硬道理,您可以:

SELECT Mid(genus,1 + InStrRev(genus," ")) AS species 

對於第2個字,如果有2個或更多;

SELECT mid(genus,InStr(genus," ")+1, instr(InStr(genus," "),genus, " ")-1) AS species 
+1

+1擊敗我。 – mwolfe02

+0

謝謝你的回覆!我嘗試了第二個選項,但它返回了#Error。我也試過第一個選項,它返回第一個單詞,而不是最後一個? – yakamafish

+0

對於沒有*空格的字段,它會失敗,是否有這樣的情況?如果是的話,你想要「」還是單個單詞? –

1

您可以使用此功能

Public Function Item(ByVal s As String, ByVal index As Long, _ 
        Optional ByVal delimiter As String = " ") As String 
    Dim i As Long, pos1 As Long, pos2 As Long 

    If index < 1 Or index > Len(s) Then 
     Item = "" 
     Exit Function 
    End If 
    s = s & delimiter 
    pos2 = 1 - Len(delimiter) 
    For i = 1 To index 
     pos1 = pos2 + Len(delimiter) 
     pos2 = InStr(pos1, s, delimiter, vbBinaryCompare) 
     If pos2 = 0 Then 
      Item = "" 
      Exit Function 
     End If 
    Next i 
    Item = Mid$(s, pos1, pos2 - pos1) 
End Function 

測試

Item("asdas df 4354 sdf", 3) 

產生

"4354" 

在SELECT語句

SELECT 
    Item(genus, 1) AS word1, 
    Item(genus, 2) AS word2, 
    Item(genus, 3) AS word3 
FROM 
    <tablename>;