2012-03-02 47 views
0

我正在嘗試編寫一個Do循環,它將輸入一個長字符串,並返回電子郵件地址之前的空間位置和之後的空間位置。使用InStr()我已經能夠找到電子郵件地址的結尾。現在我需要找到開始,然後使用Mid()來拉出地址。我發現InStrRev()應該從一個字符串的末尾開始,然後搜索,但是看看它出現的實際手冊,它只是給出了字符的第二個實例。例如:InStrRev()問題

我的字符串是:

請拍我的電子郵件。我的電子郵箱:[email protected]如果你不能打電話給我。

我到目前爲止所做的是返回@的地方,在這種情況下,如果是42.然後我使用InStr()返回@之後的第一個「」的位置。在這種情況下,52.我希望返回第一個「」之前的位置。在這種情況下,它應該是37.我的計劃是使用Mid(37,15)。十五是差異52 & 37.我嘗試過使用InStrRev()返回37,但無法讓它工作。有什麼建議麼?下面是我的代碼。

x = 2 

Do 

Cells(x, 11).Select 
Cells(x, 11).Value = (InStrRev(Cells(x, 9), Cells(x, 2), " ")) 

x = x + 1 

On Error Resume Next 

Loop Until Cells(x, 2).Value = "" 

其中(x,9)是@和地點(X,2)是字符串。

回答

3
' Find the @ symbol 
Dim atPosition As Integer 
atPosition = InStr(cellValue, "@") 
' check if found here 

' Find the space after the @ 
Dim secondSpacePosition As Integer 
secondSpacePosition = InStr(atPosition, cellValue, " ") 
' check if found here 

' Find the space before the @ 
Dim firstSpacePosition As Integer 
firstSpacePosition = InstrRev(cellValue, " ", atPosition) ' beware, the arguments differ a little 
' check if found here 

Dim email As String 
email = Mid(cellvalue, firstSpacePosition + 1, secondSpacePosition - firstSpacePosition - 1) 
7

或者也許,如果你需要的是電子郵件地址:

Function GetEmail(longstr As String) As String 

GetEmail = Filter(Split(longstr, " "), "@")(0) 

End Function 

一般來說,循環應避免在Excel中,因爲它是緩慢的,下面的會做你的代碼沒有循環:

Columns(12).Cells(1).Resize(Columns(11).Cells(2).End(xlDown).Row - 1, 1).Offset(1).Value = _ 
      Application.Transpose(Filter(Split(Join(Application.Transpose(Columns(11).Value), " "), " "), "@")) 
+0

很好地完成,+1 – Jesse 2012-03-02 21:16:04

+0

+1我不知道'Filter'。 – 2012-03-03 09:18:54

+0

感謝+ 1s,過濾器和拆分是在Excel VBA中最有用的東西之一,NB與Filter的事情是,它返回部分匹配,這就是爲什麼它在這裏工作,但需要一些漂亮的字符串操作來返回只完整匹配。 – SWa 2012-03-04 19:29:27