VBA Excel:如何将字符从一个单元格复制到另一个

时间:2019-02-13 10:30:41

标签: excel vba

我是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。

Here and example in sheet

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

1 个答案:

答案 0 :(得分:0)

我认为这会对您有所帮助

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

结束子