简体   繁体   English

如果一个单元格包含一个(或多个)Chr(10)字符但不包含其他字符,如何删除?

[英]How to delete a cell if it contains one (or more) Chr(10) characters, but no other characters?

I have a small script that sort of does what I need it to do, but I'm afraid at some point there will be more than 4 characters in a cell and I don't want to delete it. 我有一个小的脚本,可以完成我需要做的事情,但是恐怕在某个时候,一个单元格中会有超过4个字符,并且我不想删除它。 The logic that I want to employ is as follows: 我要采用的逻辑如下:

If any cell in BB1:BB10 contains ONLY Chr(10) then move the contents of the cells below up one cell. 如果BB1:BB10中的任何单元格仅包含Chr(10),则将单元格的内容向下移动一个单元格。 Something like this 像这样

Public Sub CheckHisMethod()
    Dim i As Integer
    i = 1
    For i = 10 To 1 Step -1
        If Excel.ActiveSheet.Range("BB" & i).Value = Chr(10) Then        ' or =vblf or =chr$(10)
            Excel.ActiveSheet.Range("BB" & i).Delete Shift:=xlUp
        End If
    Next i
    MsgBox "Done"
End Sub

But...I don't want to delete the Chr(10) from each cell, I only want to delete the cell, and move the cell below up one cell, if the cell contains ONLY Chr(10). 但是...我不想从每个单元格中删除Chr(10),我只想删除该单元格,如果该单元格仅包含Chr(10),则将其移动到一个单元格下方。 How can I do that? 我怎样才能做到这一点?

Please try the following. 请尝试以下方法。 It removes all CHR(10) and then it checks if the length of the resulting string is 0, meaning all characters in the cell are CHR(10) . 它删除所有CHR(10) ,然后检查结果字符串的长度是否为0,这意味着单元格中的所有字符均为CHR(10)

Public Sub CheckHisMethod()
    Dim i As Integer
    i = 1
    For i = 10 To 1 Step -1
        If Len(Replace(Excel.ActiveSheet.Range("BB" & i).Value,Chr(10),"")) = 0 Then        ' or =vblf or =chr$(10)
            Excel.ActiveSheet.Range("BB" & i).Delete Shift:=xlUp
        End If
    Next i
    MsgBox "Done"
End Sub

I'd personally use a regular expression for this - it will likely be much faster than other string manipulations: 我个人为此使用正则表达式-它可能比其他字符串操作要快得多:

'Add a reference to Microsoft VBScript Regular Expressions 5.5
Public Sub CheckHisMethod()
    Dim i As Integer
    With New RegExp
        .Pattern = "^[\n]+$"
        .MultiLine = True
        For i = 10 To 1 Step -1
            If .Test(Excel.ActiveSheet.Range("BB" & i).Value) Then
                Excel.ActiveSheet.Range("BB" & i).Delete Shift:=xlUp
            End If
        Next i
    End With
    MsgBox "Done"
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM