如何创建具有下拉值的VB框并单击按钮

时间:2014-01-07 14:15:10

标签: excel excel-vba vba

我有以下代码来自动登录网站:


Sub Auto_open()

login

End Sub


Sub login()
Dim IntExpl As Object
Set IntExpl = CreateObject("InternetExplorer.Application")
Dim dd As Object
Dim dd1 As Object
Dim dd2 As Object
Dim dd3 As Object

With IntExpl
      .navigate Worksheets("Workbook").Range("B2")
      .Visible = True
     ' If (.Document.getElementById("LoginUsername").exist) Then
       Do Until IntExpl.ReadyState = 4
       Loop
       Set dd = .Document.getElementById("LoginUsername")
       dd.Value = Worksheets("Workbook").Range("C2")
       dd.Click
       Set dd1 = .Document.getElementById("LoginPassword")
       dd1.Value = Worksheets("Workbook").Range("D2")
       dd1.Click
       Set dd2 = .Document.getElementById("loginBtn")
       dd2.Click

End With
End Sub

和工作簿:

Website    Url              Login id               Password
HPS      Masasas .com            0000123        1234
Webex    asasas .com             0000123        1234

现在......

我想在vb中创建一个宏..当宏运行它时,如下面的窗口:

  1. 应打开一个小窗口,其中有一个“网站”下拉菜单,其中包含网站列中的所有值。
  2. 当用户选择特定网站时:应该在marco中使用该网址,用户名,密码。

1 个答案:

答案 0 :(得分:0)

听起来您想要创建用户表单。为此,请从VBA窗口中选择“插入”和“用户表单”。从那里,添加一个组合框和一个命令按钮。您可以使用此代码使用以下选项填充组合框:

Private Sub UserForm_Initialize() 'We want the box to fill as soon as the form appears
Dim sites As Range

For Each sites In Range("B2:B3") 'Change this to suit your actual range
  Me.ComboBox1.AddItem sites.Value
  Next sites

End Sub

要执行代码的命令按钮,请使用:

Private Sub CommandButton1_Click()
Dim siteName As String
Dim URL As String
Dim user As String
Dim password As String
Dim site As Range
Dim IntExpl As Object
Set IntExpl = CreateObject("InternetExplorer.Application")
Dim dd As Object

siteName = UserForm1.ComboBox1.Value
Set site = Range("B2:B3").Find(siteName, ,xlValues,xlWhole)
'These variables will let you log in using arbitrary credentials instead of ones called explicitly
URL = site.Offset(0,1)
user = site.Offset(0,2)
password = site.Offset(0,3)

With IntExpl
  .navigate URL
  .Visible = True
   Do Until IntExpl.ReadyState = 4
   Loop
   Set dd = .Document.getElementById("LoginUsername")
   dd.Value = user
   dd.Click
   Set dd = .Document.getElementById("LoginPassword")
   dd1.Value = password
   dd1.Click
   Set dd = .Document.getElementById("loginBtn")
   dd.Click

 End With
End Sub

我希望这会有所帮助。干杯!