我有一个Excel表单,它从80行工作表的每一行读取数据,并将每个单元格填充到一个文本框中。
初始表格的代码如下。
Private Sub UserForm_Initialize()
txtbox_revri_idnum.Text = Worksheets("Risk&Issues").Range("A4").Value
txtbox_revri_projname.Text = Worksheets("Risk&Issues").Range("B4").Value
txtbox_revri_isrefnum.Text = Worksheets("Risk&Issues").Range("C4").Value
txtbox_revri_riskrefnum.Text = Worksheets("Risk&Issues").Range("D4").Value
...
txtbox_revri_projname.SetFocus
End Sub
理想情况下,我想要做的是当按下“下一个”按钮时,下一行(A5,B5,C5,D5 ......)被解析为一个数组,并且使用下一行的数据。相反,“前一个”按钮将反向(A3,B3,C3,D3 ......)。基本上,我想在工作表中上下导航,在新文本框中查看每个单元格的整行。
我已经尝试了各种VBA组合(记住我是VBA的新手,虽然确实有一些Java和PHP经验)。我的“下一个”按钮当前的代码包含以下代码。
Private Sub button_revri_next_Click()
txtbox_revri_idnum.Text = ActiveCell.Next.Text
...
End Sub
谢谢......我知道你们比我更聪明!
答案 0 :(得分:0)
您可以使用.Offset
来实现您的目标。
已经过测试
Dim i As Long, j As Long
Dim rng As Range
Private Sub UserForm_Initialize()
Set rng = Worksheets("Risk&Issues").Range("A4")
i = 0: j = 1
txtbox_revri_idnum.Text = rng.Offset(i).Value
txtbox_revri_projname.Text = rng.Offset(i, j).Value: j = j + 1
txtbox_revri_isrefnum.Text = rng.Offset(i, j).Value: j = j + 1
txtbox_revri_riskrefnum.Text = rng.Offset(i, j).Value: j = j + 1
'
'
txtbox_revri_projname.SetFocus
End Sub
'~~> Next Button
Private Sub button_revri_next_Click()
i = i + 1: j = 1
If i > (Sheets("Risk&Issues").Rows.Count - 4) Then
MsgBox "Max rows Reached"
Exit Sub
End If
txtbox_revri_idnum.Text = rng.Offset(i).Value
txtbox_revri_projname.Text = rng.Offset(i, j).Value: j = j + 1
txtbox_revri_isrefnum.Text = rng.Offset(i, j).Value: j = j + 1
txtbox_revri_riskrefnum.Text = rng.Offset(i, j).Value: j = j + 1
'
'
txtbox_revri_projname.SetFocus
End Sub
类似上一个按钮
'~~> Previous Button
Private Sub button_revri_prev_Click()
i = i - 1: j = 1
If i < 0 Then
MsgBox "1st Row Reached"
Exit Sub
End If
txtbox_revri_idnum.Text = rng.Offset(i).Value
txtbox_revri_projname.Text = rng.Offset(i, j).Value: j = j + 1
txtbox_revri_isrefnum.Text = rng.Offset(i, j).Value: j = j + 1
txtbox_revri_riskrefnum.Text = rng.Offset(i, j).Value: j = j + 1
'
'
txtbox_revri_projname.SetFocus
End Sub