如何验证excel单元格字符长度使用宏代码? [英] How to validate excel cell characters length use macro code?

查看:248
本文介绍了如何验证excel单元格字符长度使用宏代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在excel cell中只允许设置15个字符。我在excel中使用数据(DATA Tab)验证来给出excel cell的范围。当我输入字母时,它正在工作。如果我复制超过15个字符并且粘贴在单元格中验证不起作用如何在excel cell.how中设置验证为excel编写宏。



我尝试过:



i使用数据选项卡进行验证但不工作

解决方案

试试这个...... 。



创建一个命名范围,其中包含要限制为15个字符的所有单元格。对于下面的代码示例,我使用了一个命名范围:Limit15



然后,在ThisWorkbook对象代码窗口中使用Workbook_SheetChange事件来检查长度输入的数据...





 选项 明确 

私有 Sub Workbook_SheetChange( ByVal Sh As 对象 ByVal 目标作为范围)

Dim rngLimit As 范围
设置 rngLimit =范围( Limit15

Dim rng 作为范围

对于 每个 rng 目标' 可能有多个单元格被更改
' 检查单元格更改是否属于指定范围
如果 相交(rng,rngLimit) < span class =code-keyword> Nothing 然后

' 检查条目的长度是否大于15
如果 Len(rng) > 15 然后
' < span class =code-comment>发出警告信息
MsgBox 不能超过15个字符......,vbCritical, 文字太长了!

' 将文本截断为15个字符
rng =左(rng, 15
结束 如果
结束 如果
下一步
结束 Sub


I want to set only 15 characters allowed in excel cell.i use data(DATA Tab) validation in excel to give range of the excel cell.it is working when i type the letters.if i copy more then 15 characters and paste in the cell the validation is not working how to set the validation in excel cell.how to write the macro for excel.

What I have tried:

i use data tab for validation but not working

解决方案

Try this....

Create a named range that includes all of the cells that you want to limit to 15 characters. For the code example below I used a named range: "Limit15"

Then, in the "ThisWorkbook" object code window use the "Workbook_SheetChange" event to check the length of the data entered...


Option Explicit

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    Dim rngLimit As Range
    Set rngLimit = Range("Limit15")
    
    Dim rng As Range
    
    For Each rng In Target  ' there may be more than one cell being changed
        'check if cell changed is part of the named range
        If Not Intersect(rng, rngLimit) Is Nothing Then
        
            'check if the length of the entry is greater than 15
            If Len(rng) > 15 Then
                'give a warning message
                MsgBox "Can't be more than 15 characters...", vbCritical, "Text too long!"
                
                'truncate the text to be 15 characters
                rng = Left(rng, 15)
            End If
        End If
    Next
End Sub


这篇关于如何验证excel单元格字符长度使用宏代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆