2017-04-08 31 views
0

我正在使用以下代碼從Excel工作表中的表格數據填充用戶表單,並嘗試使用下一個和上一個按鈕來循環訪問表格中的先前條目併成功完成。使用此代碼,上一個按鈕選擇上一行並將其加載到用戶窗體中。下一個按鈕選擇下一行並將其加載到用戶窗體中。在Excel導航中達到極限的提示信息用戶表格

問題:我想限制循環僅限於表格(從工作表中的行339到390)。我想修復此代碼以限制導航到表格並顯示有關第一條記錄和最後一條記錄的警報消息。我已經修復並測試了「下一步」按鈕的代碼,但代碼爲上一個按鈕不起作用。

分享整個代碼爲您的審查和建議,將不勝感激。

Private Sub cmdGetNext_Click() 

Range("B339").Select 
ActiveCell.End(xlDown).Select 
lastRow = ActiveCell.Row 
currentrow = currentrow + 1 
If currentrow = lastRow + 1 Then 
    currentrow = lastRow 
    MsgBox "You have reached the last entered data!" 
End If 

txtmeas.Text = Cells(currentrow, 2).Value 
txtsource.Text = Cells(currentrow, 4).Value 
cmbmatric.Text = Cells(currentrow, 6).Value 

End Sub 

Private Sub cmdPreviousData_Click() 

currentrow = currentrow - 1 
If currentrow > 1 Then 
    txtmeas.Text = Cells(currentrow, 2).Value 
    txtsource.Text = Cells(currentrow, 4).Value 
    cmbmatric.Text = Cells(currentrow, 6).Value 
ElseIf currentrow = 1 Then 
    MsgBox "This is your first record!" 
    currentrow = currentrow + 1 
End If 

End Sub 
+0

您是否在下面的答案中測試了代碼?任何反饋 ? –

+0

嗨Sha,是的,我試過了,但沒有解決問題。我在這裏分享的代碼是完整的功能和工作,唯一的問題是它不會停在我的桌子上的第一個rom,但繼續移動到前面的行。但對於下一個數據按鈕,它工作得很好,並顯示消息。所以唯一的辦法是將其限制在第一行。爲了更清楚地說明,我在不同的行上有多個表,並在每個表中應用相同的代碼。如果您從第1行(A1)開始在表格上嘗試此代碼,則這對兩個方向(上一個和下一個)都是完美的,但對於其餘表格不適用。 – user7828601

+0

我感謝您的時間和協助Shai Rado! – user7828601

回答

0

我會在模塊級定義常量,表示要設置表的第一行:Const TblFirstRow

然後,在下面,而不是Range("B339"),你可以使用Range("B" & TblFirstRow)這將是更動態的修改在未來。

代碼

Option Explicit 

' define a variable at the module level, for first row of the table 
Const TblFirstRow As Long = 339 

Private Sub cmdGetNext_Click() 

Dim LastRow As Long, CurrentRow As Long 

' get last row (not skipping blank cells) 
LastRow = Range("B" & TblFirstRow).End(xlDown).Row 

If CurrentRow + 1 > LastRow Then 
    CurrentRow = LastRow 
    MsgBox "You have reached the last entered data!" 
Else 
    CurrentRow = CurrentRow + 1 
End If 

txtmeas.Text = Cells(CurrentRow, 2).Value 
txtsource.Text = Cells(CurrentRow, 4).Value 
cmbmatric.Text = Cells(CurrentRow, 6).Value 

End Sub 

'================================================================ 

Private Sub cmdPreviousData_Click() 

If CurrentRow - 1 < TblFirstRow Then 
    CurrentRow = TblFirstRow 
    MsgBox "This is your first record!" 
Else 
    CurrentRow = CurrentRow - 1 
End If 

txtmeas.Text = Cells(CurrentRow, 2).Value 
txtsource.Text = Cells(CurrentRow, 4).Value 
cmbmatric.Text = Cells(CurrentRow, 6).Value 

End Sub 
0

我會改變 「ELSEIF currentrow = 1,則」 到 「其他」。

如果你從currentrow = 1開始並運行cmdPreviousData_Click(),那麼你在第一行(currentrow = currentrow - 1)中將currentrow的值從1減小到0。那麼你的if語句沒有運行,因爲0不是> 1,你的elseif也不會運行,因爲0 <> 1。

+0

嗨查爾斯,我試過了,但沒有奏效。請參閱我對Shai Rado解決方案的評論,其中更詳細地解釋了我的問題。感謝你的協助! – user7828601

相關問題