2012-07-16 45 views
5

Tôi đang xây dựng một dự án và tôi hiểu rằng Excel 2003 hỗ trợ nhập dữ liệu từ các trang web bên ngoài thông qua "Dữ liệu -> Nhập Dữ liệu Ngoài -> Truy vấn Web Mới".Nhập dữ liệu vào Excel 2003 bằng một trang đăng nhập

này có thể được thực hiện thông qua vài bước được liệt kê ở đây: http://www.internet4classrooms.com/excel_import.htm

Tuy nhiên, các trang web tôi đang nhập dữ liệu từ một trang web nội bộ (Intranet) và nó đòi hỏi một mọi login tôi truy cập vào nó.

Trang web không nhớ mật khẩu và mỗi khi tôi nhấn nút "nhập", nó không làm bất cứ điều gì do đăng nhập.

Làm cách nào để nhắc nhập tên người dùng + mật khẩu và đăng nhập vào trang web trong khi nhập dữ liệu từ một trang web bên ngoài trong Excel 2003?

+0

Có thể để bạn có thể thay đổi mã trên máy chủ mạng nội bộ? – seeker

+0

Loại dữ liệu nào? Bạn có thể lấy nó theo cách khác không? Bạn có thể sử dụng MSXML hoặc IE tự động hóa để lấy nó thay thế không? Câu trả lời này có hữu ích không? http://stackoverflow.com/a/11216467/190829 – JimmyPena

Trả lời

2

Tôi đã thực hiện điều này khoảng một năm trước và như JimmyPena đã đề xuất, tự động hóa IE có thể là cách để đi. Điều này sẽ trông phức tạp hơn nhiều sau đó bạn đã mong đợi nhưng tôi tin rằng, tôi đã dành hàng giờ cố gắng tìm một cách đơn giản và không thể tìm thấy một.

Dành chút thời gian để tìm hiểu về HTML và đối tượng DOM. Nó có vẻ như quá mức cần thiết cho những gì bạn đang làm nhưng nó sẽ có ích trên đường nếu bạn muốn nhận dữ liệu từ các trang web. Dưới đây là một kịch bản để giúp bạn chỉ đi đúng hướng:

  1. Tạo một UserForm với hai textbox và một nút
  2. TextBox1 sẽ là đầu vào username và TextBox2 sẽ là mật khẩu của bạn
  3. Bạn nên mặt nạ mật khẩu đầu vào bằng cách chọn ký tự mật khẩu trong cửa sổ thuộc tính (Nhấn F4 trong Trình soạn thảo VBA, chọn hộp văn bản 2 từ trình đơn thả xuống và nhập ký tự bên cạnh PasswordChar)
  4. Nhấp đúp vào nút bạn vừa tạo và dán vào mã sau:

    Option Explicit 
    
    Private Sub CommandButton1_Click() 
    Const READYSTATE_COMPLETE = 4 
    Const tempDir As String = "C:\Windows\Temp\" 
    
    Dim userName$, passWord$, URL$, s_outerhtml$ ''These are strings 
    Dim IE As Object, IE_Element As Object, IE_HTMLCollection As Object 
    Dim i_file% ''This is an integer 
    Dim blnUsernameEntered As Boolean, blnPasswordEntered As Boolean, blnSheetFnd As Boolean 
    Dim ws As Excel.Worksheet 
    
    ''Test for missing username or password 
    If Me.TextBox1 = vbNullString Then MsgBox "Enter a User Name", vbOKOnly, "User Name Missing": Exit Sub 
    If Me.TextBox2 = vbNullString Then MsgBox "Enter a Password", vbOKOnly, "Password Missing": Exit Sub 
    
    ''Set the username and password based on the userform inputs 
    userName = Me.TextBox1.Value 
    passWord = Me.TextBox2.Value 
    
    ''Hide the form 
    Me.Hide 
    
    ''Enter your address to navigate to here 
    URL = "http://theofficialjbfansite.webs.com/apps/auth/login" 
    
    ''Create an Internet Explorer object if it doesn't exist 
    If IE Is Nothing Then Set IE = CreateObject("InternetExplorer.Application") 
    
    ''Make the window visible with true, hidden with false 
    IE.Visible = True 
    ''navigate to the website 
    IE.Navigate URL 
    
    '' use this loop to make wait until the webpage has loaded 
    Do While IE.Busy Or IE.readyState <> READYSTATE_COMPLETE 
        DoEvents 
    Loop 
    
    ''This is where it will get tricky - see my notes on DOM at the end of this post 
    ''build a collection of input elements 
    Set IE_HTMLCollection = IE.document.getElementsByTagName("input") 
    ''for each html element in the "input" collection 
    For Each IE_Element In IE_HTMLCollection 
        If IE_Element.Name = "email" Then IE_Element.innerText = userName: blnUsernameEntered = True 
        If IE_Element.Name = "password" Then IE_Element.innerText = passWord: blnPasswordEntered = True 
        If blnUsernameEntered = True And blnPasswordEntered = True Then Exit For 
        ''Unblock line below if you are having trouble finding the element name, 
        ''view the output in the Immediate Window (Ctrl + G in the VBA Editor) 
        ''Debug.Print IE_Element.Name 
    Next 
    
    ''Find the form and submit it 
    Set IE_HTMLCollection = IE.document.getElementsByTagName("form") 
    For Each IE_Element In IE_HTMLCollection 
        If IE_Element.Name = "loginForm" Then IE_Element.submit 
    Next 
    
    Do While IE.Busy Or IE.readyState <> READYSTATE_COMPLETE 
        DoEvents 
    Loop 
    
    ''The next line helps ensure that the html has been fully loaded 
    Application.Wait Now() + TimeValue("0:00:02") 
    s_outerhtml = IE.document.body.OuterHtml 
    i_file = FreeFile 
    
    
    ''This is a modification of some code I found at www.tek-tips.com <--great resource 
    ''the code saves a temporary copy of the webpage to your temp file 
    Open tempDir & "\tempFile.htm" For Output As #i_file 
    Print #i_file, s_outerhtml 
    
    Close #i_file 
    
    ''Creating a "Data" sheet if it doesn't exist 
    For Each ws In ThisWorkbook.Worksheets 
        If ws.Name = "Data" Then blnSheetFnd = True: Exit For 
    Next 
    
    If blnSheetFnd = False Then Sheets.Add: ActiveSheet.Name = "Data" 
    
    Sheets("Data").Cells.Clear 
    
    ''Here is your webquery, using the temporary file as its source 
    ''this is untested in 2003, if it errors out, record a macro 
    ''and replace the property that throws the error with your recorded property 
    With Sheets("Data").QueryTables.Add(Connection:= _ 
        "URL;" & tempDir & "tempFile.htm" _ 
        , Destination:=Range("$A$1")) 
        .Name = "Data" 
        .FieldNames = True 
        .RowNumbers = False 
        .FillAdjacentFormulas = False 
        .PreserveFormatting = True 
        .RefreshOnFileOpen = False 
        .BackgroundQuery = True 
        .RefreshStyle = xlInsertDeleteCells 
        .SavePassword = False 
        .SaveData = True 
        .AdjustColumnWidth = True 
        .RefreshPeriod = 0 
        .WebSelectionType = xlEntirePage 
        .WebFormatting = xlWebFormattingAll 
        .WebPreFormattedTextToColumns = True 
        .WebConsecutiveDelimitersAsOne = True 
        .WebSingleBlockTextImport = False 
        .WebDisableDateRecognition = False 
        .WebDisableRedirections = False 
        .Refresh BackgroundQuery:=False 
    End With 
    
    ''delete the temporary file 
    Kill tempDir & "\tempFile.htm" 
    
    ''clean up after yourself, foo!! 
    IE.Quit 
    Set IE = Nothing 
    Set IE_HTMLCollection = Nothing 
    Unload UserForm1 
    
    End Sub 
    
  5. Thay đổi URL vào website của bạn và sửa đổi các getelement phương pháp để làm việc với trang web của bạn

Phần khó khăn nhất đối với một người nào đó không quen với HTML và DOM (Document Object Model) sẽ tìm kiếm chính xác các yếu tố trên trang.

Một mẹo hay là sử dụng Công cụ dành cho nhà phát triển của Internet Explorer. Mở trang mạng nội bộ của bạn trong IE và nhấn F12. Thao tác này sẽ mở Công cụ nhà phát triển. Nhấp vào biểu tượng mũi tên (mũi tên chỉ lên và sang trái) trên thanh công cụ và chuyển về trang mạng nội bộ của bạn. Di chuột qua trang và bạn sẽ thấy các hộp màu xanh được vẽ xung quanh mỗi phần tử. Di chuột qua tên đăng nhập tên người dùng và nhấp vào hộp nhập liệu. Điều này sẽ làm nổi bật HTML trong mã nguồn.

Từ đây bạn có thể xác định id phần tử, tên, tên thẻ và lớp nếu nó có. Thực hiện một số nghiên cứu trên getelementbyID, getelementsbytagname, v.v. hoặc đi qua đoạn mã ở trên để có cảm nhận về cách hoạt động của nó.

Lưu ý cuối cùng, nếu trang mạng nội bộ của bạn có phần tử biểu mẫu, bạn sẽ phải lấy đối tượng biểu mẫu với các phương pháp getelement ở trên và gửi nó với .submit. Nếu trang sử dụng đối tượng nút, hãy lấy phần tử nút và sử dụng .click. Chúc may mắn!

0

Không chắc chắn nếu nó vẫn còn có liên quan nhưng tôi có một giải pháp cho điều này thông qua một macro

Sau đây là các bước sau:

1: macro được lưu lại nhập truy vấn web mới (bất cứ điều gì sẽ làm)

2: Làm mới tất cả các truy vấn của bạn.

Chỉnh sửa truy vấn web của bạn để bao gồm inline username/password.

Dưới đây là vĩ mô của tôi:

Sub xmlUpdate() 
'This will enable the import of our XML data. The first part is a dummy import, to authenticate the Excel file with the iJento servers. The second part (Web_Query_1 is the actual import) 
'The sheet is initially inserted as "Dummy" and then promptly deleted. 
    Sheets.Add.Name = "Dummy" 
    ActiveWorkbook.XmlImport URL:= _ 
     "https://USERNAME:[email protected]/query/app?service=file=201" _ 
     , ImportMap:=Nothing, Overwrite:=True, Destination:=Range("$A$1") 
    Sheets("Dummy").Select 
    Application.DisplayAlerts = False 
    ActiveWindow.SelectedSheets.Delete 
    ActiveWorkbook.XmlMaps("Web_Query_1").DataBinding.Refresh 
    End Sub 

Các vấn đề liên quan