通过excel中的字符串循环,用Alphabet替换Chars

时间:2016-06-23 20:24:46

标签: sql string excel vba loops

我正在使用Excel中的字符串,尝试用字母(按顺序)替换字符(忽略空格,短划线和句点)。 这些字符串位于单个单元格中。我只是想一次做一个单元格。 防爆。 SG6 -099将变成ABC -DEF 和3F5234-42- GA将变为ABCDEF-GH-IJ

这些字符串不会超过26个字符。

这可能吗?

提前致谢

2 个答案:

答案 0 :(得分:0)

我能够组合两个潜艇(一个我有,另一个我发现)。这是如何工作的?

Function replace_Text(ByVal cel as Range) as String


Dim editText$
editText = cel.Value

Dim i&, k&
k = 1
For i = 1 To Len(editText)
    If IsLetter(Mid(editText, i, 1)) Then
        editText = WorksheetFunction.Substitute(editText, Mid(editText, i, 1), Chr$(64 + k), 1)
        k = k + 1
    End If
Next i

replace_Text = editText
End Function

Function IsLetter(strValue As String) As Boolean
' https://techniclee.wordpress.com/2010/07/21/isletter-function-for-vba/
    Dim intPos As Integer
    For intPos = 1 To Len(strValue)
        Select Case Asc(Mid(strValue, intPos, 1))
            Case 48 To 57, 65 To 90, 97 To 122
                IsLetter = True
            Case Else
                IsLetter = False
                Exit For
        End Select
    Next
End Function

在单元格中,键入=text_Replace(A1),其中A1是带字符串的单元格。

答案 1 :(得分:0)

这是我最终使用的。它将输出填充到相邻的单元格

实施例。 080110- 0015将是输入     ABCDEF-GHIJ将是输出

Private Sub Worksheet_Change(ByVal Target As Range)


If Not Application.Intersect(Range("A1:A6"), Range(Target.Address)) Is Nothing Then
Call replace_Text("A", "1")

End If
End Sub

以上就是我如何称呼这个功能。

    Sub replace_Text(C As String, R As String)


Set cel = Range(C & R)

Dim editText$
editText = cel.Value

Dim i&, k&
k = 1
For i = 1 To Len(editText)
    If IsLetter(Mid(editText, i, 1)) Then
        Select Case (InStr(editText, Chr$(64 + k)) > 0)
        Case True
        editText = WorksheetFunction.Substitute(editText, Mid(editText, i, 1), Chr$(64 + k), 1)
        k = k + 1
        Case False
        editText = WorksheetFunction.Replace(editText, i, 1, Chr$(64 + k))
        k = k + 1
       End Select

       ElseIf IsNum(Mid(editText, i, 1)) Then
       editText = WorksheetFunction.Substitute(editText, Mid(editText, i, 1), Chr$(64 + k), 1)
        k = k + 1
    End If
Next i

Dim cel2

Set cel2 = Range("B" & R)
cel2.Value = editText


End Sub

Function IsNum(strValue As String) As Boolean
    Dim intPos As Integer
    For intPos = 1 To Len(strValue)
        Select Case Asc(Mid(strValue, intPos, 1))
            Case 47 To 57, 47 To 57
                IsNum = True
            Case Else
                IsNum = False
                Exit For
        End Select
    Next
End Function

Function IsLetter(strValue As String) As Boolean
    Dim intPos As Integer
    For intPos = 1 To Len(strValue)
        Select Case Asc(Mid(strValue, intPos, 1))
            Case 65 To 90, 97 To 122
                IsLetter = True
            Case Else
                IsLetter = False
                Exit For
        End Select
    Next
End Function