我有一列具有以下格式:
RMB-2018-726/12
RMB-2019-27/16
RMB-2019-160/21
RMB-2019-259/6
RMB-2019-433/2
现在,我需要检查最后一位或斜线之后的数字,如果是一位数字,请添加零,否则保留该值(用于排序)。我已经使用texttocolumn编写了一个代码,然后len然后合并了列,但是看来我的解决方案很长,但是可以按照我的需要工作。 为了学习,我想知道是否还有其他工作或更有效的方法来做到这一点。
'Insert zero on single digit claim number
Dim myLastRow As Long
myLastRow = Worksheets(ActiveSheet.Name).Range("A1").End(xlDown).Row
Columns("J:M").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove 'Insert 4 new columns
'Column 1 = Batch Number; Column 2 = Claim Number; Column 3 = add zero on single digit; Column 4 = merge Column 1 + 3
Range("I2:I" & myLastRow).TextToColumns _
Destination:=Range("J2"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=True, Other:=True, OtherChar:= _
"/" 'TextToColumn the Batch Column = Column 1
Application.CutCopyMode = False
Range("L2:L" & myLastRow).FormulaR1C1 = "=IF(LEN(RC[-1])=1,""0"","""")&RC[-1]" 'add zero on single digit only = Column 3
Range("M2:M" & myLastRow).FormulaR1C1 = "=RC[-3]&""/""&RC[-1]" 'combine the batch = Column 4
Range("M2:M" & myLastRow).Copy
Range("I2:I" & myLastRow).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False 'Where the original batch column
Columns("J:M").Delete
Columns("I:I").EntireColumn.AutoFit
答案 0 :(得分:1)
也许这可以帮助
Sub test()
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Sheet1")
colLatter = "A"
LastRow = ws.Cells(ws.Rows.Count, colLatter).End(xlUp).Row
valArr = ws.Range(colLatter & "1:" & colLatter & LastRow).Value
For i = LBound(valArr) To UBound(valArr)
If valArr(i, 1) <> "" Then
sStr = Split(valArr(i, 1), "/")
valArr(i, 1) = sStr(0) & "/" & Format(sStr(1), "00")
End If
Next i
ws.Range(colLatter & "1").Resize(UBound(valArr), 1) = valArr
End Sub
答案 1 :(得分:1)
这是一个简单的模式,我一直使用它来高效地更新Range值。
Sub FormatIDs()
Dim data
Dim Target As Range
Dim BackSlashIndex As Long, r As Long
With ActiveSheet
Set Target = .Range("A1", .Cells(Rows.Count, 1).End(xlUp))
End With
data = Target.Value
For r = 1 To UBound(data)
BackSlashIndex = InStrRev(data(r, 1), "/")
If Len(data(r, 1)) - BackSlashIndex = 1 Then
data(r, 1) = Left(data(r, 1), Len(data(r, 1)) - 1) & "0" & Right(data(r, 1), 1)
End If
Next
Target.Value = data
End Sub
答案 2 :(得分:1)
仅供参考,无需vba即可完成
=LEFT(A1,FIND("/",A1))&IF(MID(A1,LEN(A1)-2,1)="/",RIGHT(A1,2),"0"&RIGHT(A1,1))
或者,如果需要,还可以在斜杠前添加一个零(根据对另一个答案的评论中的要求):
=LEFT(A1,9)&IF(MID(A1,13,1)="/",MID(A1,10,4),"0"&MID(A1,10,3))&IF(MID(A1,LEN(A1)-2,1)="/",RIGHT(A1,2),"0"&RIGHT(A1,1))
请注意,没有任何更多的并发症(例如,在斜线前可能有一位数字的可能性),并且这很快就会变得笨拙,因此对于可扩展性,vba绝对是更好的选择。