Lala's tower

엑셀 자동 입력 매크로 2

엑셀 자동 입력 매크로 2

2024-06-15 21:51:24

네이버 뉴스의 타이틀을 자동으로 수집하여 엑셀에 자동 기입하는 엑셀 자동 입력 매크로 코드를 정리하였습니다.

뉴스 제목 수집 엑셀 자동 입력 매크로 실행 결과 화면입니다.

네이버 뉴스 엑셀 자동 입력 매크로

실행하면 네이버 뉴스의 현재 주요 뉴스의 제목을 자동으로 엑셀 A열에 자동 기입해주는 매크로입니다.

위 화면이 실행 결과 입니다.

Alt+F11 VBA편집기에서 아래 코드를 붙여 넣고 도구 메뉴 참조에 아래 2가지를 체크합니다.

Microsoft Internet Controls
Microsoft HTML Object Library

실행하면 위와 같은 결과가 자동 채워집니다.

혹시, 정상 실행되지 않으면 뉴스 제목의 class명이 변경된 경우일 수 있습니다.

네이버 뉴스를 브라우저에서 열고 개발자 화면(크롬에서 F12)의 Elements에서 뉴스 제목에 해당하는 class명을 찾아 "sa_text_title" 부분에 기입해주시면 됩니다.

' 엑셀 자동 입력 매크로 뉴스 자동 수집
Sub GetNaverNewsTitles()    Dim ie As Object
    Dim html As Object    Dim headlines As Object
    Dim headline As Object    Dim ws As Worksheet
    Dim i As Integer
    ' Create a new Internet Explorer instance    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = False ' Set to True if you want to see the IE window
    ' Navigate to Naver News    ie.Navigate "https://news.naver.com/main/main.nhn?mode=LSD&mid=shm&sid1=100" ' Example URL for Politics section
    ' Wait for the page to fully load
    Do While ie.Busy Or ie.ReadyState <> 4        DoEvents
    Loop
    ' Get the HTML document
    Set html = ie.Document
    ' Get the headlines (adjust the selector based on the webpage structure)    Set headlines = html.getElementsByClassName("sa_text_title")
    ' Set the worksheet
    Set ws = ThisWorkbook.Sheets(1)    ws.Cells.Clear ' Clear existing content
    ' Loop through the headlines and write them to the worksheet
    i = 1    For Each headline In headlines
        ws.Cells(i, 1).Value = headline.innerText        i = i + 1
    Next headline
    ' Clean up
    ie.Quit    Set ie = Nothing
    Set html = Nothing    Set headlines = Nothing
End Sub

엑셀 자동 입력 매크로 1