【问题标题】:How to replace the contents of a cell based on row header?如何根据行标题替换单元格的内容?
【发布时间】:2013-02-11 04:49:24
【问题描述】:

我需要在第 1 行(a1 到 dv1)中的每个单元格中搜索“doc1”在该行的后续单元格中后跟“doc2”的实例。然后我需要将包含“doc1”的单元格下方的单元格中的内容与包含“doc2”的单元格下方的单元格中的内容连接起来,用逗号分隔,并替换单元格中的文本在包含“doc1”的单元格下方。

因此,例如,如果 a1 有“doc1”,b1 有“doc2”,a2 有“7”,b2 有“8”,那么我需要将 a2 替换为“7, 8”。

任何帮助将不胜感激。

谢谢, 艾米

【问题讨论】:

    标签: string excel vba search concatenation


    【解决方案1】:

    这是 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
    

    以下是测试结果:

    【讨论】:

    • 非常感谢您的回复。这似乎还没有正常工作。字符串包含“doc1”和“doc2”但不“等于”doc1 和 doc2 是否重要?此外,应该将 Cells(1, CurrCol + 1).Value = "doc2" 改为: Cells(1, CurrCol + 1).String = "doc2" 吗?谢谢!
    • 从您的问题来看,我认为它们是 doc1 和 doc2 的硬编码值 - 如果值“包含”doc1 和 doc2,我将在几秒钟内更新我的代码。 .Value 有效 - 不知道 .String
    • 效果很好。谢谢!
    • 还有一个问题:如果我只想在 doc2 下方的单元格不为空白的情况下进行连接,这是插入的正确代码吗? If (Cells(1, CurrCol + 1).Value) > 0 Then...
    • 关闭 - 因为它是一个字符串,如果你也不想要空白,试试 if Trim(cells(1,CurrCol+1).value) "" then
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2017-01-14
    • 2012-07-09
    相关资源
    最近更新 更多