关于排序:排序,删除重复和空白,只返回excel vba数组中的数字

sort, remove duplicates and blanks, return numbers only in an excel vba array

在用户表单中,我有一个启用多行的文本框。我希望用户在文本框中输入数字,每个数字都在一个新行中,然后单击命令按钮。命令按钮应将文本存储到数组中,按升序排序,删除重复项和空白以及非数字,然后将数据返回到从范围 I3.

开始的 Excel 工作表

我尝试编码但未能排序、删除空格和非数字。此外,excel表中的输出不被识别为数字:(

在我的简单代码中,当在文本框中输入以下文本时

1
2
3
4
5
6
7
1
2
3
4

6
5

excel表上的输出是

1
2
3
4
5
6
7
5

1
2
3
4
6

这是我的试验.. 任何帮助将不胜感激

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Private Sub CommandButton1_Click()
Dim strText() As String

Dim i As Long, k As Long

k = 3
    strText = Split(TextBox3.Text, Chr(10))


    For i = 0 To UBound(strText)
        Sheet3.Cells(k, 9).Value = strText(i)
        k = k + 1
    Next i

With Sheet3
.Range("I3:I" & k).RemoveDuplicates Columns:=1, Header:=xlNo
.Range("I3:I" & k).Sort Key1:=.Range("I3"), Order1:=xlAscending
End With
End Sub

试试下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Private Sub CommandButton1_Click()
    Dim strText() As String
    Dim rng As Range
    Dim c As Range


    strText = Split(TextBox3.Text, Chr(10))
    With Sheet1
        'clear previous content
        .Range(.Cells(3, 9), .Cells(.Rows.Count, 9).End(xlUp)).ClearContents
        Set rng = .Cells(3, 9).Resize(UBound(strText)+1)
    End With

    rng = Application.Transpose(strText)
    rng.Replace Chr(13),""
    For Each c In rng
        If Not IsNumeric(c) Then c =""
    Next

    With rng
        .NumberFormat ="0"
        .Value = .Value
        .RemoveDuplicates Columns:=1, Header:=xlNo
        .Sort Key1:=.Cells(1, 1), Order1:=xlAscending
    End With

End Sub

注意事项:

  • .Range(.Cells(3, 9), .Cells(.Rows.Count, 9).End(xlUp)).ClearContents 行从 I 列中删除以前的数据
  • rng = Application.Transpose(strText) 行将所有数据写入 I 列中,无循环
  • 如果 value 不是数字,我们用空字符串替换它:If Not IsNumeric(c) Then c ="" 然后使用 RemoveDuplicates 删除
  • .NumberFormat ="0" 行设置范围内的数字格式。第 .Value = .Value 行将所有"以文本形式存储的数字"转换为"以数字形式存储的数字"