其实字数10是一个临界点,10以上,字号开始变化插入空格的代码不起作用,因此不会出错,7以上,误差尚未累积到肉眼可以观察的程度,因此看起来也是正常的。
我的代码如下,测试结果和你的一样:
Dim fl As String = ProjectPath & "结果.xls"
Dim s0,s1,s2,s3 As String
Dim chr As MSExcel.Characters
s0 = " "
s1 = "品牌:中国牌"
s2 = "品名:"
s3 = "一二" '三四五六七八九十一二三四五六七八九十
Dim App As New MSExcel.Application
App.displayAlerts = False
Dim Wb As MSExcel.WorkBook = App.WorkBooks.Open(fl)
Dim Ws As MSExcel.WorkSheet = Wb.WorkSheets(1)
Dim Rg As MSExcel.Range = Ws.Range("A3")
Rg.value = s1 & s0 & s2 & s3
chr= Rg.Characters((s1 & s0 & s2).length + 1,s3.length)
Dim i As Integer
Dim defFontSize = Rg.Font.size
Dim Range = ws.Range("A3")
Dim width = Rg.width *4/3
Dim graphics As Graphics = Forms("窗口2").baseform.CreateGraphics
Dim sizeF = graphics.MeasureString(s1 & s2, new Font("宋体", defFontSize))
width = width - sizeF.width
For i = defFontSize*2 To 1 Step -1
sizeF = graphics.MeasureString(s3, new Font("宋体", i/2))
If sizeF.width <= width Then
chr.font.size = i/2
Exit For
End If
Next
i = 0
If chr.font.size = defFontSize Then
Dim sizeF0 = graphics.MeasureString(s0, new Font("宋体",defFontSize))
width = Rg.width
MessageBox.Show("格子=" & width)
sizeF = graphics.MeasureString(s1 & s0 & s2 & s3, new Font("宋体", Rg.font.size))
width = width - sizeF.width *3/4
MessageBox.Show("字长=" & sizeF.width)
width = width/sizeF0.width
MessageBox.Show("差比=" & width)
If width > 1 Then
i = CInt(width)
Else
i = 0
End If
End If
If i > 0 Then
s0 = New String(" ", i)
MessageBox.Show("i=" & i)
Dim s33 = graphics.MeasureString(s0, new Font("宋体", defFontSize))
MessageBox.Show("s33=" & s33.width)
Rg.value = s1 & s0 & s2 & s3
MessageBox.Show(Rg.value.length)
Rg.font.size = defFontSize
End If
wb.save
App.visible = True