2015-02-24 91 views
0

我有一個文本文件,如下所示,我需要使用宏修改excel。 以下是它的樣子(空格分隔)。然而並非所有的文本文件都是空格分隔的。使用VBA有條件地修改文本文件

"W2" "S4" SEC "W1" PF22 0.7 PRM22 0.7 PI "P2" 
"W2" "S3" SEC "W1" PF22 0.7 PM22 0.7 PI "P2" 
"W2" "S2" SEC "W1" PF22 0.7 PM22 0.7 PI "P2" 
"W2" "S1" SEC "W1" PF22 0.7 PM22 0.7 PI "P2" 

我要檢查每一行,如果該行包括「錫」和「PM」等於我在我的Excel文件的列表對,改變0.7秒值0.5。

S1 P2 
S2 P1 
S5 P1 
... ... 

我試圖修改this線程中的代碼並且不成功。

我該如何繼續?

+0

你好,我們坐在那裏每個字符集之間有1個空格嗎?我的意思是,例如,在「W2」和「S4」1空間之間以及在PF22和0.7 1空間之間。那是對的嗎? – Dubison 2015-02-24 16:52:22

+0

並且對於Pn和Sn,n可以大於9嗎?它可以是2位數字嗎? – Dubison 2015-02-24 16:53:28

+0

歡迎來到SO。請查看[如何提問](http://stackoverflow.com/help/how-to-ask),併發布您修改的代碼,以及您遇到的具體問題。 – guitarthrower 2015-02-24 16:58:34

回答

0

請參閱下面的代碼。它可能並不完美,但它是基於OP中的數據樣本進行工作的。它基於chr(34),這是"的代碼。

Sub RepStr() 
Dim lastrow As Long 
Dim srchList As Worksheet 
Dim mainList As Worksheet 
Dim sStart As Long 
Dim sStop As Long 
Dim sValue As String 
Dim pStart As Long 
Dim pSttop As Long 
Dim pValue As String 

Set srchList = Sheets("Sheet8") '<- Sn Pn list 
Set mainList = Sheets("Sheet7") '<- String List 

lastrowMain = mainList.Range("A" & Rows.Count).End(xlUp).Row 
lastrowsrch = srchList.Range("A" & Rows.Count).End(xlUp).Row 

i = 1 
While i <= lastrowMain 
    'Code based on your string is located at Column A of mainList 
    sStart = InStr(5, mainList.Range("A" & i).Value, Chr(34)) + 1 
    sStop = InStr(sStart + 1, mainList.Range("A" & i).Value, Chr(34)) 
    sValue = Mid(mainList.Range("A" & i).Value, sStart, sStop - sStart) 

    pStart = InStr(InStr(1, mainList.Range("A" & i).Value, "PI"), mainList.Range("A" & i).Value, Chr(34)) + 1 
    pStop = InStr(pStart + 1, mainList.Range("A" & i).Value, Chr(34)) 
    pValue = Mid(mainList.Range("A" & i).Value, pStart, pStop - pStart) 

    'Code based on your matching values are located at srchList Column A (S values), Column B (P values) 
    For j = 1 To lastrowsrch 
     If srchList.Range("A" & j).Value = sValue And srchList.Range("B" & j).Value = pValue Then 
      mainList.Range("A" & i).Value = Replace(mainList.Range("A" & i).Value, 0.7, 0.5) 
     End If 
    Next j 
i = i + 1 
Wend 
End Sub 
+0

非常感謝,它效果很好! – Dave 2015-02-24 21:08:00

+0

另一個問題。有沒有辦法從第三個字符串開始「 – Dave 2015-02-24 21:43:35

+0

你是指字符串中的第三個字符還是工作表中的第三行? – Dubison 2015-02-25 09:00:12