2013-02-25 39 views
2

我需要搜索第1行(a1到dv1)中的每個單元格,以查找「doc2」在該行的後續單元格中跟隨着「doc1」的實例。然後我需要將包含「doc1」的單元格下一行的內容與包含「doc2」的單元格下一行的內容連接起來,並用逗號分隔,並替換單元格內的文本在包含「doc1」的單元格下方。例如,如果a1有「doc1」,b1有「doc2」,a2有「7」,b2有「8」,那麼我需要將a2替換爲「7,8」。如何根據行標題替換單元格的內容?

任何幫助將不勝感激。

感謝, 艾米

回答

2

這裏是VBA的解決方案 - 你可以複製和粘貼VBA這一個新的模塊(第一次備份您的電子表格),然後(與F5)運行它。要快速訪問VBA,請使用alt-F11。我已將註釋中的MSGBOX語句留在註釋中。此外,代碼一直到DW1,因此它可以完成DV1。

Option Explicit 

Sub Doc1_Doc2_Merge() 

    Dim CurrCol As Integer 
    Dim CurrRow As Integer 
    Dim NewValue As String 
    Dim EndCol As String 

    For CurrRow = 1 To 50 Step 2 '(assume 50 rows - skip 2 lines each time) 
     CurrCol = 1 

     EndCol = "$DW$" & Trim(Str(CurrRow)) 
     While Cells(CurrRow, CurrCol).Address <> EndCol 

      'MsgBox Cells(CurrRow, CurrCol).Address & " " & Cells(CurrRow, CurrCol).Value 

      If InStr(Cells(CurrRow, CurrCol).Value, "doc1") > 0 Then 
       ' look at next cell 
       If InStr(Cells(CurrRow, CurrCol + 1).Value, "doc2") > 0 Then 
        If Trim(Cells(CurrRow + 1, CurrCol + 1).Value) <> "" Then 
         NewValue = Cells(CurrRow + 1, CurrCol).Value & "," & Cells(CurrRow + 1, CurrCol + 1) 
         'MsgBox "New Value is " & NewValue 
         Cells(CurrRow + 1, CurrCol).Value = NewValue 
        End If 
       End If 

      End If 

      CurrCol = CurrCol + 1 
     Wend 
    Next CurrRow 

End Sub 

以下是測試結果: enter image description here

+0

非常感謝您的回覆。這似乎還沒有正常工作。字符串是否包含「doc1」和「doc2」但不等於doc1和doc2?此外,如果Cells(1,CurrCol + 1).Value =「doc2」應該是:Cells(1,CurrCol + 1).String =「doc2」?謝謝! – user2108977 2013-02-25 23:02:57

+0

從你的問題來看,我認爲它們是doc1和doc2的硬編碼值 - 如果值「包含」doc1和doc2,我將在一秒內更新我的代碼。和.Value作品 - 不知道.String – cardmagik 2013-02-25 23:07:39

+0

精美的作品。謝謝! – user2108977 2013-02-25 23:17:05

相關問題