按行连接所有数据并删除数字

时间:2018-08-17 19:54:05

标签: excel vba excel-vba excel-formula

我需要帮助为excel编写代码,该代码将一行中的所有活动数据接成一个单元格,然后遍历所有活动行进行循环。

我遇到的问题是列和行的数量完全是随机的,因此我只需要考虑到所有现有数据即可。

最后,我希望连接中仅包含字母,因此不包含数字或“,”或其他任何内容。

如果可以,请提供帮助。

如果有帮助的话,这里是前后图像。

之前

Before

之后

After

1 个答案:

答案 0 :(得分:0)

这可能有用-宏将每个特殊字符和数字都无效。将代码复制并粘贴到VBA编辑器中的新模块中,然后运行“ CreateString”子项。

Sub CreateString()
    Dim LastRow%: LastRow = ActiveSheet.UsedRange.Rows.Count
    Dim strConcatenate$, i%, j%
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.ActiveSheet

    ws.Range("A:A").Clear
    For i = 1 To LastRow
        For j = 2 To LastColumn(i) 'Calls function "LastColumn" to get the last column of each row
            strConcatenate = strConcatenate & FindReplace(ws.Cells(i, j))
        Next j
        ws.Cells(i, 1) = strConcatenate 'This will past the finished string into column [A] in the specific row
        strConcatenate = "" 'blanks the string, so the next string in the next row is fresh
    Next i
End Sub

Function LastColumn(row%) As Integer
    Dim ws As Worksheet: Set ws = ThisWorkbook.ActiveSheet

    LastColumn = ws.Cells(row, ws.Columns.Count).End(xlToLeft).Column
End Function

Function FindReplace(CellValue$)
    Dim strPattern$: strPattern = "[^A-Za-z]+"    'Pattern to only take care of letters
    Dim strReplace$: strReplace = ""    'Replace everything else with blank
    Dim regex As Object
    Set regex = CreateObject("vbscript.regexp")

    With regex
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With
    FindReplace = regex.Replace(CellValue, strReplace) 'RegEx Function replaces the pattern with blank
End Function

示例: enter image description here