Excel VBA - 如果单元格为空输入内容,否则返回错误

时间:2016-09-19 14:58:54

标签: excel vba excel-vba

我正在尝试创建一个代表具有命名托架的仓库的数据库。这将具有登录材料的功能,并在需要时检查它们。

我的Excel工作簿有一个登录表和七个标记为行A到行G的表单,用于表示仓库中的通道。每个过道都有五个架子和多个托架。连接此信息以提供唯一的位置。我目前正在努力要求VBA检查要分配的材料的位置是否为空,如果是,则应粘贴从登录表中复制的信息。不幸的是,无论我的工作表中是什么,代码只是用“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

1 个答案:

答案 0 :(得分:3)

您使用Selection错误。首先,我将解释发生了什么,然后如何有希望解决它。

当你写

之类的东西时
Selection = "Hello"

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

相同
Selection.Value = "Hello"

您正在使用Selection = something.Activate,我认为这意味着您要选择something。它可以做到这一点,但不是你想要的。

something.Activate激活(并因此选择)单元格或范围something。它还返回布尔值True(我不知道何时返回False,也许其他人可以帮助)。因此,当执行行Selection = something.Activate时,VBA首先评估返回=的{​​{1}}右侧的内容(并且在此期间评估也选择True)。现在它将something设置为Selection.Value,因为True刚被选中,something设置为something.Value

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

不是一直更改ActiveCell,而是使用变量。像这样:

ActiveCell