Cou*_*erp 10 format excel vba excel-vba excel-2010
我在电子表格中以"Smith,J.010112.pdf"的形式列出了文件名列表.但是,它们的格式为"010112.pdf","01.01.12.pdf"和"1.01.2012.pdf".我怎么能将这些格式改为"010112.pdf"?
Joe*_*sky 26
我个人讨厌使用工作表函数可以工作的VBA,所以我已经找到了一种方法来处理工作表函数.虽然你可以将这一切都塞进一个单元格中,但我已经将它分解为单独列中的许多独立步骤,这样你就可以逐步了解它是如何工作的.
为简单起见,我假设您的文件名是A1
B1 = LEN(A1)
确定文件名的长度
C1 = SUBSTITUTE(A1,"","")
用空格替换空格
D1 = LEN(C1)
如果用空格替换空格,则查看字符串的长度
E1 = B1-D1
确定有多少个空格
F1 = SUBSTITUTE(A1,"",CHAR(8),E1)
用文件名中不能出现的特殊字符替换最后一个空格
G1 = SEARCH(CHAR(8),F1)
找到特殊字符.现在我们知道最后一个空间在哪里
H1 = LEFT(A1,G1-1)
在最后一个空格之前剥离所有内容
I1 = MID(A1,G1 + 1,255)
在最后一个空格后剥离一切
J1 = FIND(".",I1)
找到第一个点
K1 = FIND(".",I1,J1 + 1)
找到第二个点
L1 = FIND(".",I1,K1 + 1)
找到第三个点
M1 = MID(I1,1,J1-1)
找到第一个数字
N1 = MID(I1,J1 + 1,K1-J1-1)
找到第二个数字
O1 = MID(I1,K1 + 1,L1-K1-1)
找到第三个数字
P1 = TEXT(M1,"00")
填充第一个数字
Q1 = TEXT(N1,"00")
填充第二个数字
R1 = TEXT(O1,"00")
填充第三个数字
S1 = IF(ISERR(K1),M1,P1和Q1和R1)
将数字放在一起
T1 = H1&""&S1&".pdf"
将它们放在一起
这有点乱,因为Excel在20多年内没有添加一个新的字符串操作函数,所以应该很容易的事情(比如"查找最后一个空格")需要严格的诡计.
以下功能有效.我假设日期是ddmmyy格式化的,但如果是这样的话,请进行适当的调整mmddyy- 我无法从你的例子中看出来.
Function FormatThis(str As String) As String
Dim strDate As String
Dim iDateStart As Long
Dim iDateEnd As Long
Dim temp As Variant
' Pick out the date part
iDateStart = GetFirstNumPosition(str, False)
iDateEnd = GetFirstNumPosition(str, True)
strDate = Mid(str, iDateStart, iDateEnd - iDateStart + 1)
If InStr(strDate, ".") <> 0 Then
' Deal with the dot delimiters in the date
temp = Split(strDate, ".")
strDate = Format(DateSerial( _
CInt(temp(2)), CInt(temp(1)), CInt(temp(0))), "ddmmyy")
Else
' No dot delimiters... assume date is already formatted as ddmmyy
' Do nothing
End If
' Piece it together
FormatThis = Left(str, iDateStart - 1) _
& strDate & Right(str, Len(str) - iDateEnd)
End Function
Run Code Online (Sandbox Code Playgroud)
这使用以下辅助函数:
Function GetFirstNumPosition(str As String, startFromRight As Boolean) As Long
Dim i As Long
Dim startIndex As Long
Dim endIndex As Long
Dim indexStep As Integer
If startFromRight Then
startIndex = Len(str)
endIndex = 1
indexStep = -1
Else
startIndex = 1
endIndex = Len(str)
indexStep = 1
End If
For i = startIndex To endIndex Step indexStep
If Mid(str, i, 1) Like "[0-9]" Then
GetFirstNumPosition = i
Exit For
End If
Next i
End Function
Run Code Online (Sandbox Code Playgroud)
去测试:
Sub tester()
MsgBox FormatThis("Smith, J. 01.03.12.pdf")
MsgBox FormatThis("Smith, J. 010312.pdf")
MsgBox FormatThis("Smith, J. 1.03.12.pdf")
MsgBox FormatThis("Smith, J. 1.3.12.pdf")
End Sub
Run Code Online (Sandbox Code Playgroud)
他们都回来了"Smith, J. 010312.pdf".