【问题标题】:vba excel: how to copy characters from a cell to anothervba excel:如何将字符从一个单元格复制到另一个单元格
【发布时间】:2019-02-13 10:30:40
【问题描述】:

我是 VBA 领域的新手,我正在根据您的建议学习。

我已经寻找了几种解决方案,尝试了它们,但它们并不适合我的问题。

这里是链接

Find a string within a cell using VBA

How to Count the Number of a Specific Character in a Cell with Excel VBA

Which command in VBA can count the number of characters in a string variable?

我需要的是检查Input 中的字符并匹配Match list key 的可能性。匹配字符串后,复制输出中的字符 I。

如您所见,第一行很容易匹配,但在A8 单元格(例如)中有一个包含十四个字符的字符串。 在这种情况下,我需要这样,当有一个以 CMXXAB 开头的字符串时,匹配是 WT(总是!)。 当我们有 A12 时也会发生同样的事情:它以 ETRxxx 开头,并且在匹配之后将在像 JAZZ 这样的输出中开始。

【问题讨论】:

  • 如果您向我们展示您的代码,您将获得更好的帮助!
  • 好吧,我没有。我正在尝试生成一个,但我现在的经验有限????
  • JAZZWT 的规则之外,还有任何其他特殊规则?此外,您的数据屏幕截图对于进行适当的故障排除几乎毫无用处。它不能被复制/粘贴到工作表中。必须手动输入它会让那些可能会帮助您的人感到沮丧。为了使数据有用,请编辑您的问题以将其发布为文本,可能使用此Markdown Tables Generator,或者可能将工作簿(已删除敏感信息)上传到某个公共网站并在您的原始问题中发布链接。
  • 特殊规则仅适用于爵士和wt
  • 你说的CMXXAB到底是什么意思?

标签: excel vba


【解决方案1】:

我认为这会对你有所帮助:

Option Explicit

Sub test()

    Dim LastrowA As Long, i As Long, AppearA As Long, AppearB As Long
    Dim strA As String, strB As String


    With ThisWorkbook.Worksheets("Sheet1")

        LastrowA = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 1 To LastrowA

            strA = .Range("A" & i).Value
            strB = .Range("C" & i).Value

            'Check if strA appears in strB
            AppearA = InStr(1, strB, strA)
            If AppearA > 0 Then
                .Range("B" & i).Value = strA
                Exit For
            End If

            'Check if strB appears in strA
            AppearB = InStr(1, strA, strB)
            If AppearB > 0 Then
                .Range("B" & i).Value = strB
                Exit For
            End If

        Next i

    End With

End Sub

非常感谢您的帮助。 几天后,我在我的问题中找到了问题的解决方案。 事实上,这是我的解决方案,我希望能帮助任何需要这样的人。

Sub AssociazioneRotabiliPerPivot()

Dim LastrowA, LastrowC As Long, i, j As Long, AppearA As Long, AppearB As Long
Dim strA As String, strB As String

With ThisWorkbook.Worksheets("sheet1")

    LastrowA = .Cells(.Rows.count, "A").End(xlUp).Row
    LastrowC = .Cells(.Rows.count, "C").End(xlUp).Row

    For j = 1 To LastrowC   

        For i = 1 To LastrowA   

            strA = .Range("A" & i).Value
            strB = .Range("C" & j).Value

            AppearC = InStr(1, strA, strB)
            If AppearB > 0 Then
                .Range("B" & i).Value = strB
            End If

            If (InStr(1, strA, "CM") Or InStr(1, strA, "C4551R")) > 0 Then

                .Range("B" & i).Value = "WT"   

            ElseIf InStr(1, strA, "ETR425") > 0 Then   

                .Range("B" & i).Value = "JAZZ"  

            End If

        Next i

    Next j

End With

结束子

【讨论】: