2013-07-03 73 views
0

我是vba的新手,只用了几个月。我一直在学习。尽管如此,我正在尝试编写一些代码来关注各种功能。我已经编写了下面的代码,它是从用户窗体上的命令按钮启动的。该代码基本上应该是在Excel工作表中搜索一行并验证一些信息,然后采取行动。如果代码无法验证该行上的条目与用户窗体中的条目之间是否匹配,则代码将停止并显示错误消息。如果它可以验证信息匹配,则应该继续填充该行的一些信息。我意识到我编写的这段代码可能完全受到了阻碍,并且显然不够优雅,但是直到我为产品代码添加了验证后才开始工作。请有人帮忙吗?我看了看,找不到解决方案。vba中的嵌套ifs

下面是代码:

Private Sub AddDelivButton_Click() 

Sheets("Deliveries").Activate 

Dim number As Integer, rownumber As Integer, result As Long, i As Integer 
number = POTextBox.Value 
rownumber = 0 
result = 1000000 
For i = 1 To 25000 
If Cells(i, 1).Value = number Then 
    result = Cells(i, 1).Value 
    rownumber = i 
End If 
Next i 
If result = 1000000 Then 
    MsgBox "PO Number Not Found" 
    Sheets("Dashboard").Activate 
    Exit Sub 
    Else 
    Cells(rownumber, 1).Select 

ActiveCell.EntireRow.Cells(3).Select 
    If ActiveCell.Value <> ProdCodeListBox1.Value Then 
     ActiveCell.EntireRow.Cells(5).Select 
     If ActiveCell.Value <> ProdCodeListBox1.Value Then 
      ActiveCell.EntireRow.Cells(7).Select 
      If ActiveCell.Value <> ProdCodeListBox1.Value Then 
       MsgBox "Product Code Not Found" 
       Sheets("Dashboard").Activate 
       Exit Sub 
       Else 
       ActiveCell.EntireRow.Cells(10).Select 
       If ActiveCell.Value = "" Then 
        ActiveCell.Value = ProdCodeListBox1.Value 
        ActiveCell.EntireRow.Cells(11).Value = WeightTextBox1.Value 
        ActiveCell.EntireRow.Cells(12).Value = DateTextBox1.Value 
        Else 
        ActiveCell.EntireRow.Cells(13).Select 
        If ActiveCell.Value = "" Then 
         ActiveCell.Value = ProdCodeListBox1.Value 
         ActiveCell.EntireRow.Cells(14).Value = WeightTextBox1.Value 
         ActiveCell.EntireRow.Cells(15).Value = DateTextBox1.Value 
         Else 

这正好为几个迭代和保存我并没有包括所有的人都在这里空间。只要说最后两个if语句正在工作,直到我为ProdCodeListBox1添加了验证即可。

任何帮助将非常感谢!即使它是简单的我可以忽略。

谢谢!

回答

2

在你当前的代码中,你检查单元格3,5和7是否有匹配值,如果没有匹配就显示一个错误,然后退出Sub。如果单元格7匹配,您只会继续检查单元格10。如果细胞3或5的比赛,你永远不会检查对细胞10

试试这个:

ActiveCell.EntireRow.Cells(3).Select 

If ActiveCell.Value <> ProdCodeListBox1.Value Then 
    ActiveCell.EntireRow.Cells(5).Select 

    If ActiveCell.Value <> ProdCodeListBox1.Value Then 
     ActiveCell.EntireRow.Cells(7).Select 

     If ActiveCell.Value <> ProdCodeListBox1.Value Then 
      MsgBox "Product Code Not Found" 
      Sheets("Dashboard").Activate 
      Exit Sub 
     End If 
    End If 
End If 

ActiveCell.EntireRow.Cells(10).Select 
If ActiveCell.Value = "" Then 

所有ActiveCellSelect企业是不是得到特定细胞中的值的最佳方式但这是一个不同的问题

+0

非常感谢您的帮助!这很容易,立即解决了这个问题。我了解您对ActiveCell和Select的评论。我一直在教自己,但我也想学习更高效的编码。不幸的是,有时我已经写了很多行,我不想回去重做,所以我学习了一些东西。 – user2544753