以下函式執行以下操作:當前檔案夾上的
Get the full path of file which name is numbers only 最高數字。
它可以正常作業,直到檔案名大于 2139999999 ,例如 2149999999.xlsb
此行引發的錯誤 If lngNb < CLng(Split(El, ".")(0)) Then
注意:我在 windows 10 64 位上使用 office 2016 32 位。
感謝您的評論和回答。
Function Path_of_Highest_Numeric_Name(strFold As String, Optional strext As String = "*.*") As String
Dim arrD, i As Long, lastName As String, lngNb As Long, El
'Return all files name in an array
arrD = Split(CreateObject("wscript.shell").Exec("cmd /c dir """ & strFold & strext & """ /b").StdOut.ReadAll, vbCrLf)
If UBound(arrD) = -1 Then MsgBox "Nothing could be found in the path you supplied...": Exit Function
arrD(UBound(arrD)) = "@@##": arrD = Filter(arrD, "@@##", False) 'Remove the last (empty) element
For Each El In arrD 'iterate between the array elements
If IsNumeric(Split(El, ".")(0)) Then
'Compare the lngNb variable (initially 0) with the numeric value:
If lngNb < CLng(Split(El, ".")(0)) Then
'addapt lngNb like the bigger number
lngNb = CLng(Split(El, ".")(0)): lastName = El
End If
End If
Next
Path_of_Highest_Numeric_Name = strFold & lastName 'Build the necessary path
End Function
可以通過以下方式進行測驗:
Debug.Print Path_of_Highest_Numeric_Name("C:\Users\Waleed\Desktop\", "*.xls*")
uj5u.com熱心網友回復:
a 可以容納的最大數字Long(因為它是有符號的 32 位數字)是 2,147,483,647 - 因此您會溢位。
正如 Rory 建議的那樣,您可以切換到 Double 因為它有更多的有效數字。
我建議你根本不要處理數字 - 最后你無論如何都會回傳一個字串。
以下邏輯比較字串。為了防止“9”>“10”,邏輯是如果一個字串更長,它就更大。如果兩個字串的長度相同,則可以比較它們。
IsNumeric順便說一句,無論您的字串 (=filename) 有多長,該函式都能正常作業。
Dim largestNumber As String, newNumber As String, fileWithLargestNumber As String
largestNumber = ""
For Each El In arrD 'iterate between the array elements
newNumber = Split(El, ".")(0)
If IsNumeric(newNumber) Then
If Len(largestNumber) < Len(newNumber) _
Or (Len(largestNumber) = Len(newNumber) And largestNumber < newNumber) Then
largestNumber = newNumber
fileWithLargestNumber = El
End If
End If
Next
Path_of_Highest_Numeric_Name = strFold & fileWithLargestNumber
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441754.html
