我在Excel VBA中创建了一个用户窗体,我将使用它来查看和更新我的工作表中的某些记录:
UserForm1 http://im35.gulfup.com/Ay43Z.png
我似乎无法弄清楚如何使它在工作表中的状态列中包含“Y”的记录之间导航。
Sheet1 http://im36.gulfup.com/cq6CN.png
我需要用户能够通过UserForm编辑他正在查看的记录的“注释”列,以便更改保存在工作表中。 Userform上的其余文本框设置为Locked,以便它们只能显示数据。
我现在面临的问题是,我似乎只能在所有记录之间循环。我需要的是在具有“Y”作为其“状态”的那些之间导航。此外,我似乎无法弄清楚如何在表单上的“注释”框中进行更改以保存在工作表上。
任何帮助都会非常感激!
修改
以下是我对上一个按钮的代码:
If CurRecord = 0 Then CurRecord = 1
With ws
For i = 1 To (CurRecord - 1)
If Not .Range("G" & i).Value = "X" Then
TextBox1.Text = .Range("A" & i).Value
TextBox2.Text = .Range("B" & i).Value
'
'~~> And So on load the rest
'
CurRecord = i
Exit Sub
End If
Next i
If (i - 1) = lRow Then
MsgBox "End of record reached"
End If
End With
当我使用它时,它会一直跳到第一条记录。
我也尝试过:
For i = 1 To (CurRecord - 1)
但是当它到达第一条记录时,这会给我一个“超出范围”的错误。
想知道我哪里出错了?
答案 0 :(得分:2)
以下是Next
按钮的一个非常基本的示例。现在我确信您可以类似地对Previous
按钮进行编码:)
Dim ws As Worksheet
Dim lRow As Long
Dim CurRecord As Long
'~~> Load the first record
Private Sub UserForm_Initialize()
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("G" & .Rows.Count).End(xlUp).Row
For i = 2 To lRow
If .Range("G" & i).Value = "Y" Then
TextBox1.Text = .Range("A" & i).Value
TextBox2.Text = .Range("B" & i).Value
'
'~~> And So on load the rest
'
CurRecord = i
Exit For
End If
Next i
End With
End Sub
'~~> Next Button
Private Sub CommandButton3_Click()
If CurRecord = 0 Then CurRecord = 1
With ws
For i = (CurRecord + 1) To lRow
If .Range("G" & i).Value = "Y" Then
TextBox1.Text = .Range("A" & i).Value
TextBox2.Text = .Range("B" & i).Value
'
'~~> And So on load the rest
'
CurRecord = i
Exit Sub
End If
Next i
If (i - 1) = lRow Then
MsgBox "End of record reached"
End If
End With
End Sub
通过评论进行跟进
试试这个(未经测试)
'~~> Previous Button
Private Sub CommandButton2_Click()
If CurRecord = 2 Then
MsgBox "Begining of record reached"
Exit Sub
ElseIf CurRecord = 0 Then
CurRecord = 3
End If
With ws
For i = (CurRecord - 1) To 2 Step -1
If .Range("G" & i).Value = "Y" Then
TextBox1.Text = .Range("A" & i).Value
TextBox2.Text = .Range("B" & i).Value
'
'~~> And So on load the rest
'
CurRecord = i
Exit Sub
End If
Next i
If i = 2 Then
MsgBox "Begining of record reached"
End If
End With
End Sub
答案 1 :(得分:0)
如果您自动过滤“Y”,则导航将仅访问可见的行(其中包含“Y”)。简单地:
ActiveSheet.Range("$A1:$G$1").AutoFilter Field:=7, Criteria1:="Y"