Excel的VBA – 如果单元格是空的input的东西,否则返回错误

我正在尝试创build一个数据库,表示一个名为bay的仓库。 这将具有login材料的function,并在需要时检查它们。

我的excel工作簿有一张login表和七张工作表,标记为A行到G行,表示仓库中的过道。 每个过道有五个架子和一些海湾。 这些信息被连接起来以提供一个唯一的位置。 我目前正在努力要求VBA检查一个材料的位置是否为空,如果是,那么它应该粘贴从login表中复制的信息。 不幸的是,无论我的工作表中有什么,代码只是用“TRUE”填充ActiveCell,并提出我所要求的错误信息,如果不是这样。 我也尝试了IfEmpty以及相同的结果。

我的代码如下所示:

Sub LogIn() Dim Row As String Dim Location As String ' assign values to variables Worksheets("Log In").Activate Location = Cells(6, 3).Value Row = Cells(3, 3).Value ' copy new inputs to clipboard Sheets("Log In").Range("C8:C11").Copy ' find the correct location within the separate racking sheets Sheets("Row " & Row).Activate Selection = Cells.Find(What:=Location, After:=Cells(1, 1), LookIn:=xlFormulas, _ lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlNext, _ MatchCase:=False, searchformat:=False).Activate Selection = Sheets("Log In").Cells(6, 3).Value Selection = ActiveCell.Offset(0, 2).Activate ' check whether location is empty If ActiveCell.Value = "" Then ' paste new inputs onto racking sheet ActiveCell.PasteSpecial ' or return an error Else: MsgBox "The location you have selected is currently occupied" End If End Sub 

您正在使用Selection错误。 首先我会解释发生了什么,然后如何有希望解决这个问题。

当你写这样的东西

 Selection = "Hello" 

它用“你好”填充选定的单元格。 Excel不能将Selection设置为“Hello”,而是将所有选中单元格的值设置为“Hello”,即它与

 Selection.Value = "Hello" 

你正在使用Selection = something.Activate ,我假设你想selectsomething 。 这样做,但不是你想要的。

激活激活(并因此select)单元格或范围的something 。 它也返回布尔值True (我不知道什么时候会返回False ,也许别人可以帮忙)。 所以当Selection = something.Activate被执行的时候,VBA首先评估=的右边是什么,返回True (在这个评估过程中也select了something )。 现在它将Selection.Value设置为True ,因为刚才select了something.Value被设置为True


现在,您可以做的最好的事情就是停止使用“ Selection和“ Activate 。 如果您需要使用ActiveCell作为某种用户input,请将该Range设置为子开头的ActiveCell,并在需要时使用它。

而不是一直在改变ActiveCell ,使用variables。 像这样的东西:

 Dim myCell as Range '... Set myCell = Sheets("Row " & Row).Cells.Find(.... 'You should rename Row because it's already a property of Range. myCell.Value = Sheets("Log In").Cells(6, 3).Value Set myCell = myCell.Offset(0, 2) If myCell.Value = "" Then '...