我正在从VBA Excel中的dir读取文件。 阅读后,我正在写单元格中的文件。 问题是以文件名升序搜索目录。但我需要按部分文本(文件名中的数字)的顺序打印
例如:
image_100
image_120
image_1205
image_123
我需要像
那样打印的解决方案image_100
image_120
image_123
image_1205
[按照最后的价值上升] 有帮助的朋友吗?
感谢, 哈拉。
答案 0 :(得分:0)
实现这一目标的一种方法是将排序值放入另一列(我假设文件名在A列中,并在本例中使用B列作为排序字段)
Public Sub ReOrderFiles()
Columns("B:B").Clear
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("Sheet1")
Dim LastRow As Long
LastRow = sht.UsedRange.Rows(sht.UsedRange.Rows.Count).Row
Dim dr As Range
Set dr = Range("A1:A" & LastRow)
dr.Select
Dim target As Range
Dim c As Range
For Each c In dr.Cells
Set target = Range("B" & c.Row)
target.Select
If Len(c.Value2) > 0 Then
Selection.Value = "Sort" & onlyEndDigits(c.Value2)
End If
Next
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A:B")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("B:B").Clear
End Sub
最后获取数字的功能可以是
Function onlyEndDigits(s As String) As String
Dim retval As String
Dim Start As Integer
retval = ""
Start = 1
Dim i As Integer
For i = Len(s) To 1 Step -1
If Mid$(s, i, 1) >= "0" And Mid$(s, i, 1) <= "9" Then
Start = i
Else
Exit For
End If
Next
For i = Start To Len(s)
retval = retval + Mid(s, i, 1)
Next
onlyEndDigits = retval
End Function
注意此函数将忽略文件名
中其他位置出现的任何数字