问题
A previous problem I posed to the group was solved thanks to Vincent G's help.
To summarize, I have written some VBA which identifies cells formatted general like "<0" (with the symbol "<" as part of the cell value), and the VBA will change the format to a numerical format (with the "<" as part of the format) with the same number of decimal places as the original value (e.g., "<0.564" general will be changed to "< 0.564" numerical).
This code worked on a small set of test data, but when scaling up, I have run into another problem: with multiple instances of cells with teh same number of decimal places, the VBA works as intended for custom formats "< 0.0" through "< 0.00000", but for some reason it copies the same value for the first instance of "<0" it encounters into all other instances of this formatting.
It's a little painful to describe so please check out my example spreadsheet on Dropbox: the sheet has test data, the VBA, and a description of the issue.
Many thanks for your time and expertise, Christian
回答1:
Not sure I follow exactly what you're doing in that code of yours, but here's how I've done this in the past.
Sub Tester()
Dim c As Range
For Each c In Range("A2:A25")
ModifyCellNumberFormat c
Next c
End Sub
'Modify the format of a cell to include any modifier
Sub ModifyCellNumberFormat(c As Range)
Dim sModifierFormat As String, strVal As String, dotPos As Integer
Dim modifier As String
strVal = Trim(CStr(c.Value))
If strVal Like "<*" Or strVal Like ">*" Then
modifier = Left(strVal, 1)
strVal = Trim(Right(strVal, Len(strVal) - 1))
dotPos = InStr(strVal, ".")
'construct the numeric part of the format string (eg. "0.000")
If dotPos = 0 Then
sModifierFormat = "0" 'no d.p., so simple format is OK
Else
sModifierFormat = "0." & String(Len(strVal) - dotPos, "0")
End If
c.Value = strVal
c.NumberFormat = modifier & sModifierFormat 'add format to value cell
End If
End Sub
回答2:
Using @Jeeped solution to the last problem you could just do something like this. Probably could be made a bit more robust (trimming c.value before doing checks and such) but it should do what you want.
Sub test()
For Each c In Sheet1.Range("A2:A25")
If Left(c.Value, 1) = "<" Then
c.Value = Right(c.Value, Len(c.Value) - 1)
c.NumberFormat = "[>1]< 0;[>0]< 0.0####; 0; @"
End If
Next
End Sub
来源:https://stackoverflow.com/questions/38798779/vba-for-changing-multiple-cell-formats-stop-values-from-repeating