2013-02-25 83 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

相关问题