WPS Excel中配置下拉多选(VBA)

网上找到两种方案,一种利用数据选择其他单元格,也就是在其他单元格建数据。需求是模板,不合适

这里我用的VBA,踩了挺多坑,详细说下

首先更新WPS为最新版,确保可用VBA和JSA  确定使用VBA还是JSA,两种语法不同

  1.  VBA较老,语法可靠些,推荐(本文使用VBA)
  2.  JSA为新引入JS,但支持较少,不太推荐
  3.  如选择VBA,请跳转至以下链接查看详情。若为JSA,请另寻方案

 

11.7 更新:使用宏会产生在excel页面上的视图,在使用ExcelJS和JSzip解析图片的过程中会被错误识别为图片,引起图片顺序混乱的问题


VBA配置借鉴了csdn一篇博客,以下为相关链接:

CSDN-指南:https://blog.csdn.net/qq_36448758/article/details/134162812

金山文档-多选方案:https://www.kdocs.cn/article/2C6CD5AA30.html

 

以下为打开方式

 

默认为空,先创建一个新的宏再编辑

 

此处为VBA编辑,注意在红色框处写入代码

 

 

 

 

 

若不生效的话再切回WPS点击运行

 

 

最后附上版本图

 

 

 

 

以下为VBA代码

不选择值时显示空,选址值后替换空,用、间隔

复制代码
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim oldVal As String
    Dim newVal As String
    Dim delimiter As String
    delimiter = "" ' 设置分隔符

    ' 限定只在B列进行处理
    If Not Intersect(Target, Me.Range("B:B")) Is Nothing Then
        If Target.Count > 1 Then Exit Sub

        On Error Resume Next
        Application.EnableEvents = False
        newVal = Trim(Target.Value) ' 去除新值两侧空格
        Application.Undo
        oldVal = Trim(Target.Value) ' 去除旧值两侧空格

        If oldVal <> "" And newVal <> "" Then

            ' 如果最终值为空,保持为空
            If InStr(Target.Value, "") Then
                Target.Value = newVal ' 移除新值(如果它出现在开头)
            Else
                If InStr(1, oldVal, newVal) > 0 Then
                    ' 移除新值及其前面的分隔符
                    Target.Value = Replace(oldVal, delimiter & newVal, "")
                    Target.Value = Replace(Target.Value, newVal, "") ' 移除新值(如果它出现在开头)
                 Else
                     ' 新值不在旧值中,则添加它
                     If oldVal <> "" Then
                         Target.Value = oldVal & delimiter & newVal
                     Else
                         Target.Value = newVal
                     End If
                 End If
             End If
         End If

         ' 清理多余的分隔符
         Target.Value = Application.Trim(Target.Value) ' 去掉两侧空格
         If Left(Target.Value, Len(delimiter)) = delimiter Then
             Target.Value = Mid(Target.Value, Len(delimiter) + 1)
         End If
         If Right(Target.Value, Len(delimiter)) = delimiter Then
             Target.Value = Left(Target.Value, Len(Target.Value) - Len(delimiter))
         End If

         ' 如果最终值为空,保持为空
         If Target.Value = "" Then
             Target.Value = "" ' 设置为一个空字符串
         ElseIf Target.Value = "0" Then
             Target.Value = "" ' 设置为一个空字符串
         ElseIf Target.Value = 0 Then
             Target.Value = "" ' 设置为一个空字符串
         End If
     End If

 exitHandler:
     Application.EnableEvents = True
 End Sub
复制代码

 

 

 



 

posted @   m79464449p  阅读(380)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示