2016-08-12 53 views
2

我有一個項目的月度價格列表,價格列中包含金額和貨幣。我正嘗試刪除多列的貨幣。使用VBA在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代碼嗎?

+0

更改.'Range(「A1:E6」)'.Range(「B3:E6」)' – winghei

+0

謝謝!必須知道錯誤是由沒有空格的單元格值引起的 – Ava

回答

1

該代碼比你的代碼長/效率低,但是當它用完編輯單元時,它不會給你一個錯誤,至少(這是我過去已經寫過的幾乎完全準確的模塊相同的目的)。或者,如果您更新範圍以從貨幣金額開始的單元格開始,那麼您應該工作(但最後仍然出現錯誤)。您可以在MSDN Documentation中閱讀有關VBA範圍的更多信息。

它需要你添加一個VBA引用到「Microsoft VBScript Regular Expressions 5.5」,如果你還沒有檢查過。你可以在工具 - >參考中做到這一點。

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 
0

我說得對不對,讀「空間後刪除文本爲「包括這個空間」?如果是這樣的話:

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 
相關問題