在userform中,我有一个启用了多行的文本框。我希望用户在文本框中输入数字,每个数字都在一个新行中,然后单击一个命令按钮。命令按钮应将文本存储到数组中,按升序排序,删除重复项和空格以及非数字,然后将数据返回到从I3开始的Excel工作表。
我尝试编码但未能排序,删除空白和非数字。此外,Excel工作表中的输出不会被识别为数字:(
在我的简单代码中,将以下文本输入文本框
1
2
3
4
6
5
Excel工作表上的输出是
5
1
2
3
4
6
这是我的试用..任何帮助将不胜感激
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
答案 0 :(得分:0)
请尝试以下代码:
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
中写入所有数据
If Not IsNumeric(c) Then c = ""
,然后使用RemoveDuplicates
.NumberFormat = "0"
设置范围内的数字格式。行.Value = .Value
将所有“以文本形式存储的数字”转换为“以数字形式存储的数字”