使用VBA在Excel中跨多个列的空格后删除文本

时间:2016-08-12 20:27:32

标签: vba excel-vba macros excel

我有一个项目列表的月度价格,价格列有金额和货币。我想删除多列中的货币。

示例数据集: enter image description here

我写下面的宏来删​​除A1中单元格空格后的文本:E6:

Sub RemoveCurrency()
Dim cell As Range
Dim withCurrency As String
Dim PriceOnly As String
For Each cell In Worksheets("Sheet1").Range("A1:E6")
    withCurrency = cell.Value
    PriceOnly = Left(withCurrency, InStr(withCurrency, " ") - 1)
    cell.Value = PriceOnly
    Next cell
End Sub

运行后,它给我一个VB运行时错误'5': 无效的过程调用或参数

有人可以帮忙调试我的VBA代码吗?

2 个答案:

答案 0 :(得分:1)

这段代码比你的代码长得多/效率低,但是当它用完要编辑的单元格时它不会给你一个错误,至少(这是我过去写过的模块几乎完全相同)目的)。或者,如果您更新范围以在货币金额开始的单元格处开始,则您的工作(但最后仍然是错误)。您可以在MSDN Documentation中了解有关VBA范围的更多信息。

如果您尚未检查VBA引用,则需要向“Microsoft VBScript Regular Expressions 5.5”添加VBA引用。你可以在工具 - >中做到这一点。引用。

Public Sub TruncateIDs()

    Dim strPattern As String: strPattern = "[A-Z]{1,3}"
    Dim strReplace As String: strReplace = ""
    Dim regEx As New RegExp
    Dim strInput As String
    Dim MyRange As Range

    Set MyRange = ActiveSheet.Range("B3:E6")
    ActiveSheet.Range("B3").Select

    Do While strPattern <> ""
        strInput = ActiveCell.Value

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.Test(strInput) Then
            ActiveCell = regEx.Replace(strInput, strReplace)
            ActiveCell.Offset(1, 0).Select
        ElseIf ActiveCell = "" Then
            ActiveCell.Offset(-4, 1).Select
            If ActiveCell <> "" Then
                strInput = ActiveCell.Value
                ActiveCell = regEx.Replace(strInput, strReplace)
                ActiveCell.Offset(1, 0).Select
            Else
                Exit Do
            End If
        Else
            Exit Do
        End If
    Loop

End Sub

答案 1 :(得分:0)

我是对的,请阅读&#34;删除文字后空格&#34; 为&#34;包括此空间&#34;?如果是这样的话:

Dim sStr$
        ' ...
    For Each cell In Worksheets("Sheet1").Range("A1:E6")
        ' ...
        sStr = cell.Value
        If LenB(sStr) Then cell.Value = Split(sStr, " ")(0)
            'or
        cell.Value = Split(sStr & " ", " ")(0)
        ' ...
    Next
' I'm not sure which is faster... but LenB seems to me more realiable