Excel VBA: 如何对文本框值进行四舍五入并关闭窗体
Excel VBA: 如何对文本框值进行四舍五入并关闭窗体
本文将介绍如何使用 Excel VBA 代码实现以下功能:
- 将文本框 'TextBox13' 的值四舍五入到两位小数。2. 将所有数据填写到 '销售明细表' 后自动关闭窗体。
以下是修改后的 VBA 代码:vbaPrivate Sub CommandButton2_Click() Dim ws As Worksheet Dim lastRow As Long Set ws = Sheets('销售明细表') lastRow = ws.Cells(ws.Rows.Count, 'B').End(xlUp).Row + 1 ws.Cells(lastRow, 'B').Value = ComboBox1.Value ws.Cells(lastRow, 'C').Value = ComboBox2.Value ws.Cells(lastRow, 'D').Value = ComboBox3.Value ws.Cells(lastRow, 'E').Value = TextBox5.Value ws.Cells(lastRow, 'F').Value = ComboBox4.Value ws.Cells(lastRow, 'G').Value = TextBox7.Value ws.Cells(lastRow, 'H').Value = TextBox8.Value ws.Cells(lastRow, 'I').Value = TextBox9.Value ws.Cells(lastRow, 'J').Value = TextBox10.Value ws.Cells(lastRow, 'K').Value = TextBox11.Value ws.Cells(lastRow, 'L').Value = Format(TextBox12.Value, '0%') ' 使用 Format 函数转换为百分号字符串 ws.Cells(lastRow, 'M').Value = Round(TextBox13.Value, 2) ' 四舍五入并保留两位小数 ws.Cells(lastRow, 'N').Value = TextBox14.Value ws.Cells(lastRow, 'O').Value = TextBox15.Value ws.Cells(lastRow, 'P').Value = TextBox16.Value ws.Cells(lastRow, 'Q').Value = TextBox17.Value ws.Cells(lastRow, 'S').Value = TextBox18.Value ws.Cells(lastRow, 'T').Value = ComboBox5.Value ws.Cells(lastRow, 'U').Value = TextBox20.Value With ws.Sort .SortFields.Clear .SortFields.Add Key:=ws.Range('E9:E' & lastRow), SortOn:=xlSortOnValues, Order:=xlDescending .SetRange ws.Range('B9:U' & lastRow) .Header = xlYes .Apply End With Unload Me ' 关闭窗体End Sub
代码解释:
Round(TextBox13.Value, 2): 使用Round函数将 'TextBox13' 的值四舍五入到两位小数。2.Unload Me: 在所有数据填写完成后关闭当前窗体。
使用方法:
- 将以上代码粘贴到您的 Excel VBA 编辑器中(打开 VBA 编辑器可按 Alt + F11)。2. 确保将代码放置在与您的按钮 'CommandButton2' 关联的模块中。3. 运行代码,点击按钮即可执行数据填写、四舍五入和关闭窗体的操作。
希望本文能帮助您解决 Excel VBA 中的文本框四舍五入和窗体关闭问题。
原文地址: http://www.cveoy.top/t/topic/5LS 著作权归作者所有。请勿转载和采集!