如何在EXCEL中编写个窗口输入名字 工资定位到指定的单元格并将工资输入到指定的单元格
打开Visual Basic界面 (Alt+F11)
新建一个UserForm。根据你的需求把窗体做好。
编写如下程序
Private Sub CommandButton1_Click()
Dim counter As Integer
Dim sign As Boolean
counter = 0
Row = 0
sign = False
Range("B2").Select
Do Until Selection.Offset(counter, 0).Value = ""
If TextBox1.Text = Selection.Offset(counter, 0).Value Then
sign = True
Row = counter
End If
counter = counter + 1
Loop
If sign Then
Selection.Offset(Row, 6).Value = TextBox2.Text
Else
MsgBox ("无此用户")
End If
End Sub
Private Sub UserForm_Click()
UserForm1.Hide
End Sub
2018-01-11 · 知道合伙人旅游行家
Private Sub CommandButton1_Click()
a = TextBox1.Text
b = TextBox2.Value
x = Range("b65536").End(xlUp).Row
c = 0
For i = 1 To x + 1
If Cells(i, 2) = a Then
Cells(i, 8) = b
c = 1
ElseIf i = x + 1 And c = 0 Then
MsgBox "没有这个人,请检查", vbOKOnly
End If
Next
End Sub
打开VBA编辑器,点击插入-用户窗体
绘制窗体如图:
邮件点击按钮“查找并插入”--选择查看代码
输入以上代码。
双击ThisWorkbook,输入以下代码:
Private Sub Workbook_Open()
UserForm1.Show
End Sub
这样打开工作表时就能直接打开窗体了。
答:
1、使用"工具"--"引用",勾选"Microsoft Visual Basic For Application Extensibility Library"
2、使用VBIDE,还需要打开"信任中心"--勾选"信任对VBA工程对象模型的访问"
3、无需插入窗体,只需插入"模块",然后复制下面代码:
Sub MakeForm()
Dim TempForm As Object
Dim NewButton
Dim NewLabel
Dim NewTextBox
Dim i As Integer
Dim Line As Integer
On Error Resume Next
Application.VBE.MainWindow.Visible = False
Set TempForm = ThisWorkbook.VBProject. _
VBComponents.Add(3)
With TempForm
.Properties("Caption") = "加班工资录入"
.Properties("Width") = 300
.Properties("Height") = 200
End With
Set NewButton = TempForm.Designer.Controls _
.Add("forms.CommandButton.1")
With NewButton
.Caption = "填写"
.Left = 200
.Top = 140
End With
For i = 1 To 2
Set NewLabel = TempForm.Designer.Controls.Add("Forms.Label.1")
Set NewTextBox = TempForm.Designer.Controls.Add("Forms.TextBox.1")
With NewLabel
.Caption = Application.Choose(i, "姓名", "奖金")
.Left = 20 * i ^ 3
.Top = 40
End With
With NewTextBox
.Name = Application.Choose(i, "Employee", "Bonus")
.Left = 20 * i ^ 3 + 25
.Top = 40
End With
Next
With TempForm.CodeModule
Line = .CountOfLines
.InsertLines Line + 1, "Sub CommandButton1_Click()"
.InsertLines Line + 2, "Set FindRng = Range(""B:B"").Find(what:=Employee.Text, lookat:=xlPart)"
.InsertLines Line + 3, "FindRng.Offset(0, 6) = Bonus.Text"
.InsertLines Line + 4, "End Sub"
End With
VBA.UserForms.Add(TempForm.Name).Show
ThisWorkbook.VBProject.VBComponents.Remove TempForm
End Sub
Private Sub CommandButton1_Click()
If Me.TextBox1 <> "" And Me.TextBox2 <> "" Then
If IsNumeric(Me.TextBox2.Value) Then
Dim CXrng As Range, K As Byte
For Each CXrng In Range("B4:B" & Range("B65536").End(xlUp).Row)
If CXrng.Value = Me.TextBox1.Text Then
CXrng.Offset(0, 6).Value = Val(Me.TextBox2.Value)
K = 1
Exit For
End If
Next
Else
MsgBox "工资录入非数值!!"
GoTo 100
End If
Else
MsgBox "数据录入不完整!"
GoTo 100
End If
If K <> 1 Then
MsgBox "没有找到可用姓名!"
End If
100:
End Sub