2013-07-03 74 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