Excel添加复选框、批量添加

Excel添加复选框
office版本:专业增强版2021
在这里插入图片描述

打开开发工具

文件→选项→自定义功能区→主选项卡勾选开发工具
在这里插入图片描述

添加复选框

开发工具→插入→选中表单控件:复选框
在这里插入图片描述

使用VBA批量添加复选框

开发工具→宏→输入方法名→点击创建→输入代码→切回Excel文件→选择执行范围→宏执行
在这里插入图片描述
代码如下:

Sub 复选框()
  
    Application.ScreenUpdating = False
  
    Dim rng As Range
    Dim topLeftCell As Range
    Dim chkBoxTop As Double
    Dim chkBoxLeft As Double
    Dim chkBoxWidth As Double
    Dim chkBoxHeight As Double
      
    For Each rng In Selection
        ' 获取rng的左上角单元格
        Set topLeftCell = rng.Cells(1, 1)
          
        ' 计算复选框的位置和大小
        chkBoxTop = topLeftCell.Top + (rng.Height / 2) - (topLeftCell.RowHeight / 2)
        chkBoxLeft = topLeftCell.Left + (rng.Width / 2) - (topLeftCell.Width / 2)
        chkBoxWidth = rng.Width / 2
        chkBoxHeight = rng.Height / 2
          
        ' 检查rng的值是否为"TRUE"
        If rng.Value = True Then
            With Sheet1.CheckBoxes.Add(Top:=chkBoxTop, Left:=chkBoxLeft, Width:=chkBoxWidth, Height:=chkBoxHeigh)
                .Value = xlOn
                .Caption = ""
            rng.Value = Null
            End With
        Else
            With Sheet1.CheckBoxes.Add(Top:=chkBoxTop, Left:=chkBoxLeft, Width:=chkBoxWidth, Height:=chkBoxHeight)
                .Value = xlOff
                .Caption = ""
            rng.Value = Null
            End With
        End If
    Next rng
      
    Application.ScreenUpdating = True
End Sub

在这里插入图片描述

执行成功后的效果如下:
在这里插入图片描述
目前存在问题:复选框的位置不够居中。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值