因此,我目前正在接受#34;预期结束声明"运行提供的代码时出错。我知道问题在于Sub Searched函数的编写方式。我不确定从哪里开始,但您应该能够从所提供的代码中感受到我需要做的事情。 Sub Searched仅作为独立工作,而不是初始化功能。
初始化
Private Sub UserForm_Initialize()
TextBox1.Text = Selection.Value
TextBox2.Text = Searched Sheets("CashHour1").Range("B2:E60"), Selection
End Sub
在初始化函数中自动填充文本框的命令
Sub Searched(Rnge As Range, E_name As String)
On Error Resume Next
Sal = Application.WorksheetFunction.VLookup(E_name, Rnge, 2, False)
Sal1 = Application.WorksheetFunction.VLookup(E_name, Rnge, 3, False)
If Len(E_name) = 0 Then
MsgBox "Select an employee"
ElseIf Len(Sal) < 1 Then
Hours = "OFF"
Else
Hours = Sal & " - " & Sal1
End If
End Sub
答案 0 :(得分:1)
Searched
是子程序,而不是函数,因此无法返回值。
有两种方法可以解决这个问题,一种方法是将Searched
更改为函数,但我可能只是修改Searched
子例程以接受TextBox参数。
Searched Sheets("CashHour1").Range("B2:E60"), Selection.Value, TextBox2
因此修改sub以接受文本框参数:
Searched(Rnge As Range, E_name As String, tb as MSForms.TextBox)
On Error Resume Next
Sal = Application.WorksheetFunction.VLookup(E_name, Rnge, 2, False)
Sal1 = Application.WorksheetFunction.VLookup(E_name, Rnge, 3, False)
If Len(E_name) = 0 Then
MsgBox "Select an employee"
ElseIf Len(Sal) < 1 Then
Hours = "OFF"
Else
Hours = Sal & " - " & Sal1
End If
'## Write to the textbox:
tb.Text = Hours
End Sub
注意您有很多未声明的变量并且您的错误处理不存在,因此这可能仍会引发一些问题,例如Len(E_Name) = 0
然后TextBox1.Text将是0
...
另请参阅此答案,了解为什么不在代码中使用Selection
: