有没有可能在VBA中修复或声明单元格的types?

我知道在VBA中,我们可以做到

Cells(4, 2).Value = 100 'the cell is an integer Cells(4, 2).Value = True 'the cell is Boolean Cells(4, 2).Value = "abc" 'the cell is Text 

是否有可能修复或声明一个单元格的types,例如,让Cells(4,2)只接受布尔值,这样分配一个IntegerTextCells(4, 2)会给出错误?

[编辑此解决scheme可以从VBA实现,但不能从VBA使用,即仍可以将单元格值设置为VBA中的任何内容(尽pipe不是在Excel表单中手动)。 不确定OP实际需要什么。 ]

使用数据validation。

你可以通过VBA来做到这一点:

 Range("A1").Validation.Add Type:=xlValidateList, Formula1:="TRUE,FALSE" 

或手动:(在Excel 2003中:数据>validation…)

在这里输入图像说明

现在,您可以在单元格A1中只input布尔值TRUEFALSE 。 如果您尝试input其他内容,例如一个数字:

在这里输入图像说明

使用数据validation,你也可以限制单元格只接受数字,只接受整数,一定长度的文本,基本上任何东西。 例如,要只接受文本而不接受数字,则可以使用Allow:Custom,Formula: =NOT(ISNUMBER(A1))

如果您确实希望指定单元格types,则不能。 就我所知,VBA中的所有单元格都包含不同的数据types。

如果你的意思是变体的数据types,那么当然可以这样做。 这是一个build议,它有点快而肮脏,但它的工作原理。 您需要将它放在工作表代码模块中。 请注意,它不testing如果你的布尔范围,int范围,任何相交,可能会导致你一些问题,如果他们这样做。

 Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo handler Dim cell As Range, _ boolRng As Range, _ intRng As Range Set boolRng = Union(Sheet1.Range("A1:B2"), Sheet1.Range("E:E")) Set intRng = Union(Sheet1.Range("B7:K12"), Sheet1.Range("M:M")) If Not Intersect(Target, boolRng) Is Nothing Then For Each cell In Intersect(Target, boolRng) If cell.Value <> "" Then cell.Value = CBool(cell.Value) End If Next cell End If If Not Intersect(Target, intRng) Is Nothing Then For Each cell In Intersect(Target, intRng) If cell.Value <> "" Then cell.Value = CInt(cell.Value) End If Next cell End If Exit Sub handler: Select Case Err.Number Case 13 'Type mismatch, raised when cint/cbool/c*** fails cell.Value = "" Resume Next Case Else Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext End Select End Sub 

编辑:我注意到你想提出一个错误,如果值分配不正确,你可以在error handling部分做到这一点。 代替

 Cell.value = "" Resume Next 

你可以使用

 Err.Raise ISuggestAnEnumForErrorNumbers, "Sheet1.Worksheet_Change(Event)", "Attempted to assign wrong type to cell." 

我是第二个JFC关于使用数据validation的build议。

为了testing它,将这个代码放入一个模块( TRIED AND TESTED

 Sub Sample() With Sheets("Sheet1").Range("A1") .Validation.Delete .Validation.Add Type:=xlValidateList, Formula1:="TRUE,FALSE" .Value = "SID" End With End Sub 

这在相关的表格中

 Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo Whoa If Not Intersect(Target, Range("A1")) Is Nothing Then Application.EnableEvents = False On Error Resume Next If Not Target.SpecialCells(xlCellTypeSameValidation).Cells.Count < 1 Then Dim currentValidation As Excel.Validation Set currentValidation = Target.Validation If currentValidation.Type = xlValidateList Then '~~> I am using INSTR. If you want you can split it using "," as delim '~~> and check for the value. If Not InStr(1, currentValidation.Formula1, Target.Value, vbTextCompare) Then MsgBox "Incorrect Value" Target.ClearContents End If End If End If On Error GoTo 0 End If LetsContinue: Application.EnableEvents = True Exit Sub Whoa: MsgBox Err.Description Resume LetsContinue End Sub 

现在尝试在模块中运行Sub Sample()