簡體   English   中英

Trim如何在Excel VBA中工作?

[英]How does Trim work in Excel VBA?

我有以下代碼來擺脫中間空格,換行和修剪

但是Trim不起作用。 可能是什么原因?

Sub Replace()

  With Sheets("Input_Data").Range("A1:A6300")
  'With Sheets("Input_Limits").Range("A1:A6300")

    .Cells.Replace "  ", " ", xlPart, xlByRows, False
    .Cells.Replace vbLf, "", xlPart, xlByRows, False
    '.Cells.Trim

  End With

End Sub

它給:

錯誤-對象不支持此屬性方法

您不能在范圍上使用Trim Trim文檔指出:

修剪( 字符串
必需的字符串參數是任何有效的字符串表達式。

另外, Trim不適合您的任務,因為它不會刪除字符串中的空格。 在文檔中提到了這一點(添加了重點):

返回一個Variant(String),其中包含指定字符串的副本,不包含前導空格(LTrim),尾隨空格(RTrim) 或前導和尾隨空格(Trim)

以下代碼將滿足您的要求。 請注意,我正在對活動工作表中的所有單元格進行修剪操作; 如果那不是您想要的,顯然您可以對其進行編輯...

Sub trimAll()
  Dim c As Range

  For Each c In ActiveSheet.UsedRange.Cells
    If Not (IsEmpty(c) Or IsError(c) Or IsFormula(c)) Then
      c.Value = Trim(c.Value)
    End If
  Next c

  With ActiveSheet.UsedRange.Cells
    .Cells.Replace "  ", " ", xlPart, xlByRows, False
    .Cells.Replace vbLf, "", xlPart, xlByRows, False
  End With

End Sub

Function IsFormula(c)
  ' use this to test for formulas - don't edit those or they become values!
  IsFormula = True
  On Error Resume Next
  If Left(c.Formula, 1) = "=" Then IsFormula = True Else IsFormula = False
End Function

由於Trim不支持范圍,因此可以添加以下內容:

Dim c as Cell
For each c in .Cells
  c.Value = Trim(c.Value)
Next c

免責聲明:未經測試。 請參閱其他答案以獲取更完整的解決方案。

Sub DescTrim(Cx As Integer)  
    Dim Rx As Integer: Rx = 5 'Start at row 5  
    Dim STrimmed As String  
        For Rx = 5 To ActiveSheet.UsedRange.Rows.Count  
            STrimmed = Trim(Cells(Rx, Cx).Value)  
            While InStr(STrimmed, chr(32) & (chr(32))  
                STrimmed = Replace(STrimmed, Chr(32) & Chr(32), chr(32))  
            Wend  
            Cells(Rx, Cx).Value = STrimmed  
        Next  
End Sub  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM