简体   繁体   中英

Excel VBA string manipulation

I need to do some string manipulation and it's kinda beating me real good.

I need to extract some substrings from a string.

This is the string:

"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"

I need to extract each module, one module means from --------------------------------- to Design: 1h . So the substrings should look like:

"[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"

Please help!

You can use the Split function, and use your '------' string as a delimiter. Eg:

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

By now allModules is a string array holding each module, but skip the 1st (it's the text up to the first '----').

If the '------' string is not fixed and must be read from the same text, then use InStr to search for "Effects of change", find the following end of line (also with InStr ) and use Mid to extract the '------' . Like:

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)

and use moduleDelimiter in stead of the '-----' string in Split .

You can use the InStr and Mid functions:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM