繁体   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