2014-02-13 198 views
1

我需要做一些字符串操作,它有點擊敗我真正的好。Excel VBA字符串操作

我需要從字符串中提取一些子字符串。

這是字符串:

"Modified by: Coanda Oana Amalia coanoa1 (coanoa1) on Mon Oct 14 08:53:11 EEST 2013 
Modified Fields: 
Actual target date: 17.10.2013 GMT+02:00 
Effects of change: --------------------------------- 
[ErrH] 
Regenerate error configuration. 
Effort: 2h 
Design: 1h 
--------------------------------- 
[Ist] 
Rename error. 
Effort: 1h 
Design: 1h 
--------------------------------- 
[RTE] 
Rename the runnable according to the change. 
Check internal errors mapping. 
Effort: 2h 
Design: 1h" 

我需要提取每個模塊,一個模塊是指從--------------------------------- Design: 1h。因此,子應該是這樣的:

"[RTE] 
Rename the runnable according to the change. 
Check internal errors mapping. 
Effort: 2h 
Design: 1h" 
"[ErrH] 
Regenerate error configuration. 
Effort: 2h 
Design: 1h" 
"[Ist] 
Rename error. 
Effort: 1h 
Design: 1h" 

請幫幫忙!

+0

嘗試使用'Split'。那應該不是太難 – sam092

回答

0

您可以使用Split函數,並使用您的'------'字符串作爲分隔符。例如: -

Dim bigText As String 
bigText = ... 
Dim allModules() As String 
allModules = Split(bigText, "---------------------------------") 

現在allModules是一個字符串數組保存每個模塊,但跳過1日(它的文本到第一「----」)。

如果'------'字符串是不固定的,並且必須來自同一文本閱讀,然後用InStr搜索「變化帶來的影響」,找到線(也有InStr)以下端使用Mid提取'------' 。像:

Const delimiterPreAmble As String = "Effects of change: " 
Dim startDelimiterPos As Long 
startDelimiterPos = InStr(bigText, delimiterPreAmble) + Len(delimiterPreAmble) 
Dim endDelimiterPos = InStr(startDelimiterPos, bigText, vbNewLine) 
Dim moduleDelimiter As String 
moduleDelimiter = Mid(bigText, startDelimiterPos, endDelimiterPos - startDelimiterPos) 

Split使用moduleDelimiter'-----'字符串代替。

+0

謝謝很多人! –

0

您可以使用InStr和Mid函數:

Dim s as String, sPart as String, remainingString as String 

s = "your initial string here" 
remainingString = s 
While(InStr(1,remainingString,"--") > 0) 
    sPart = Mid(remainingString , InStr(1,remainingString ,"--"), _ 
    InStr(1,remainingString ,"Design: 1h") - InStr (1,remainingString ,"--") + Len("Design: 1h")) 
    remainingString = Mid(remainingString , _ 
    InStr(1,remainingString ,"Design: 1h") + Len("Design: 1h")) 
    Msgbox sPart 
    '' do whatever with sPart 
Wend 
+0

非常感謝! –