本帖最后由 Tingamm 于 2024-11-24 23:32 编辑
VBA代码如下:
[Visual Basic] 纯文本查看 复制代码 Sub 字体调整()
ActiveCell.Font.Size = 10
ActiveCell.WrapText = False
ActiveCell.ShrinkToFit = False
For i = 10 To 1 Step -0.5
If Len(ActiveCell) <= Fix(ActiveCell.MergeArea.Width / i) * Fix(ActiveCell.MergeArea.Height / (i + 2)) Then
ActiveCell.WrapText = True
ActiveCell.Font.Size = i
Exit For
Else
ActiveCell.ShrinkToFit = True
End If
Next
End Sub
2024.11.24更新
在网上抄了一段按关键字多选工作表的代码,加上自己摸索之后更新新的代码如下:
[Visual Basic] 纯文本查看 复制代码 Dim maxSize As Long, minSize As Long
Dim keyWord As String
Sub 自动调整表格()
inputSize:
Call 输入字号
inputKey:
Call 输入关键字
Dim sameMban As Integer
sameMban = MsgBox("本次所调整含有该关键字的表格模板及数据格式是否一致?", vbYesNo, "提示")
If sameMban = vbYes Then Call 批量调整
If sameMban = vbNo Then Call 逐个调整
Dim continueTzheng As Integer
continueTzheng = MsgBox("是否继续调整?", vbYesNo, "提示")
If continueTzheng = vbYes Then
Dim sameSize As Integer
sameSize = MsgBox("是否以相同字号调整?", vbYesNo, "提示")
If sameSize = vbYes Then GoTo inputKey
If sameSize = vbNo Then GoTo inputSize
End If
If continueTzheng = vbNo Then End
End Sub
Sub 输入字号()
maxSize = Application.InputBox("设置最大字号(默认字号)", "设置字号", "10")
If maxSize = vbnot Then End
minSize = Application.InputBox("设置最小字号", "设置字号", "1")
If minSize = vbnot Then End
End Sub
Sub 输入关键字()
keyWord = Application.InputBox("请输入表名关键字", "输入关键字", "组1")
If keyWord = "False" Then End
End Sub
Sub 批量调整()
Dim bFlag As Boolean
Dim oSht As Worksheet
bFlag = True
For Each oSht In Sheets
If InStr(oSht.Name, keyWord) Then
If bFlag Then
oSht.Select
bFlag = False
Else
oSht.Select Replace:=False
End If
End If
Next
Call 遍历选定区域调整文本
Call 返回目录
End Sub
Sub 逐个调整()
Dim shtName As Worksheet, getName As String
For Each shtName In Worksheets()
shtName.Activate
getName = ActiveSheet.Name
If InStr(getName, keyWord) Then
ActiveSheet.Select
Call 遍历选定区域调整文本
End If
Next
Call 返回目录
End Sub
Sub 遍历选定区域调整文本()
On Error GoTo error
Dim arrAddress(), rngSelect
Set rngSelect = Application.InputBox("选定调整区域", Type:=8)
Dim rng As Range
For Each rng In Range(rngSelect.Address(0, 0))
rng.Select
Call 调整文本
Next
GoTo continue
error:
If rngSelect = 0 Then
Call 返回目录
End
End If
continue:
End Sub
Sub 调整文本()
ActiveCell.Font.Size = maxSize
ActiveCell.WrapText = False
ActiveCell.ShrinkToFit = False
ActiveCell.Interior.ColorIndex = 0
For i = maxSize To minSize Step -0.5
Dim textLen As Long
textLen = LenB(StrConv(ActiveCell, vbFromUnicode))
Dim estimatedCapacity As Long, maxCapacity As Long
estimatedCapacity = (Fix(ActiveCell.MergeArea.Width / (i + 0.07)) * Fix(ActiveCell.MergeArea.Height / (i + 2.05))) * 1.95
maxCapacity = (Fix(ActiveCell.MergeArea.Width / (minSize + 0.07)) * Fix(ActiveCell.MergeArea.Height / (minSize + 2.05))) * 1.95
If textLen <= estimatedCapacity Then
ActiveCell.WrapText = True
ActiveCell.Font.Size = i
Exit For
Else
If textLen > maxCapacity Then
MsgBox "字符过多!已将单元格背景颜色设置为黑色!", , "提示"
ActiveCell.Interior.Color = RGB(0, 0, 0)
Exit For
End If
End If
Next
End Sub
最后附模块文件。
|