问题
What I need is custom format to change values according to these rules:
- If "/" is absent and number's length is less than 6, add zeroes to the begining.
- If "/" is present and number's length before"/" is less than 6, add zeroes to the begining.
- If "/" is present and number's length after "/" is 1, add zero before last character.
- If "/" is present and number's length after "/" is 2, leave as it is.
- Total length of string with "/" would be 8, without it - 6
Unformatted data:
-534
1083
386840/2
12345/10
Desired result:
000534
001083
38684002
01234510
What I came up so far:
000000;000000;0 is pretty obvious part, value without "/" will be read as number anyway. If it was a number, I would use [>1000]0 or something like that but it doesn't work with Text as far as I understood.
Formula I'm using (just for now) instead of desirable custom format:
=IF(ISERROR(FIND("/";A1));
CONCATENATE(REPT("0";6-LEN(A1));A1);
IF((LEN(A1)-FIND("/";A1))=1;
SUBSTITUTE(CONCATENATE(REPT("0";7-FIND("/";A1));A1);"/";"0");
SUBSTITUTE(CONCATENATE(REPT("0";7-FIND("/";A1));A1);"/";"")))
Can anyone give me a hint?
回答1:
Here is one way of accomplishing what you want using NumberFormat. The appropriate number format is generated by VBA event code.
There is a BIG disadvantage in that you will need a different number format for every unique entry that contains a "/", and the number of allowable number formats can be limiting.
However, it does not require helper columns, and does not alter the original data stored in the cell.
Anything entered in column A will be formatted according to the rules.
If a slash is present, the code will alter the numeric sections; but does not test to see that both are numeric. So abc/1 --> abc01, but you can change that if you like.
This is Worksheet code:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim FormatRange As Range, C As Range
Const Fmt As String = "000000;000000;000000;@"
Dim V As Variant
Set FormatRange = Range("A:A")
If Not Intersect(Target, FormatRange) Is Nothing Then
For Each C In Intersect(Target, FormatRange)
If InStr(C.Text, "/") = 0 Then
C.NumberFormat = Fmt
Else
V = Split(C.Text, "/")
V(0) = Format(V(0), "000000")
V(1) = Format(V(1), "00")
C.NumberFormat = ";;;" & Chr(34) & Join(V, "") & Chr(34)
End If
Next C
End If
End Sub
来源:https://stackoverflow.com/questions/46051456/excel-custom-format-check-for-character