请参阅For循环中单元格的命名范围

大家下午好,

我在VBA上有些生疏,因为我已经开始使用其他语言编程,所以我希望有人能够帮助我。

我要做什么

我有两张床单。 一个是用户填写的表单页面,另一个(Sheet1 ….我没有命名)基本上是一个数据页面。

在Sheet1内我有一个表,显示1或0取决于表单上的范围是否有特定的select。 单元格值的两列表示需要input消息的范围。 macros应该find所有的1,查找命名的范围find两列,并插入命名的范围。 不幸的是我不断收到一个应用程序或对象定义的错误。 我的代码如下:

PcentData = Sheets("Sheet1").Range("PcentData").Value If PcentData > 0 Then For Each pCell In Sheets("Sheet1").Range("PcentSwitch") If pCell.Value = 1 Then With Sheets("Payment-Deduction Form").Range(Cells(pCell.Row, pCell.Column + 2)).Validation 'Error here .Add Type:=xlValidateInputOnly .InputTitle = "Test" .InputMessage = "Test" End With End If Next pCell End If 

编辑:

我设法通过定义一个名为NamedRange的string并使其等于旧的with语句指向正确的工作表,从而确保代码从正确的工作表中抽取指定的范围。

 Dim NamedRange As String PcentData = Sheets("Sheet1").Range("PcentData").Value If PcentData > 0 Then For Each pCell In Sheets("Sheet1").Range("PcentSwitch") If pCell.Value = 1 Then NamedRange = Sheets("Sheet1").Cells(pCell.Row, pCell.Column + 2).Value MsgBox (Sheets("Sheet1").Cells(pCell.Row, pCell.Column + 2).Value) With Sheets("Payment-Deduction Form").Range(NamedRange) If .Validation Then .Validation.Delete .Validation.Add /* Error Here */ Type:=xlValidateInputOnly .InputTitle = "Test" .InputMessage = "Test" End With End If Next pCell End If 

不幸的是,我得到的错误对象不支持If .validation部分上的这个属性或方法。

也许你可以尝试这样的:

 PcentData = Sheets("Sheet1").Range("PcentData").Value If PcentData > 0 Then For Each pCell In Sheets("Sheet1").Range("PcentSwitch") If pCell.Value = 1 Then With Sheets("Payment-Deduction Form").Cells(pCell.Row, pCell.Column + 2).validation .delete .Add Type:=xlValidateInputOnly .InputTitle = "Test" .InputMessage = "Test" End With End If Next pCell End If 

我已经删除了.Range ,我已经从当前单元格删除validation。

在Vityata的帮助下,我设法find了解决问题的办法。 问题是原来的循环正在采取我想从错误的工作表查找表的位置。 我将它存储在名为“NamedRange”的variables中,并将其插入到With语句中,而不是直接将其编码到Range()中。

接下来的问题是数据validation。 它似乎不喜欢将.Validation与With语句分开,如果我需要做多个更改为单元格,我将需要多个With语句。 这是工作代码:

 Dim NamedRange As String PcentData = Sheets("Sheet1").Range("PcentData").Value If PcentData > 0 Then For Each pCell In Sheets("Sheet1").Range("PcentSwitch") If pCell.Value = 1 Then NamedRange = Sheets("Sheet1").Cells(pCell.Row, pCell.Column + 2).Value With ThisWorkbook.Sheets("Payment-Deduction Form").Range(NamedRange).Validation .Delete .Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _ :=xlBetween .IgnoreBlank = True .InCellDropdown = True .InputTitle = "test" .ErrorTitle = "" .InputMessage = "test" .ErrorMessage = "" .ShowInput = True .ShowError = True End With End If Next pCell End If 

谢谢你的帮助!