ThepExcel Logo
  • บทความ
    • Excel
      • Excel ทั่วไป
      • Excel Pivot Table
      • Excel Power Pivot
      • Power Query
      • Excel Array Formula
      • Excel VBA
      • Excel for Business
      • Excel and Maths
      • ฟังก์ชัน Excel ทั้งหมด
    • Power BI
      • Power Query
      • Data Model
      • DAX Formula
      • Power BI Report
    • Coding
      • Excel VBA
      • Python
      • Power Query M Code
    • AI
      • ChatGPT
      • Stable Diffusion
      • MidJourney
    • Highlights : บทความแนะนำ
    • คลิปวีดีโอ
  • อบรม
    • อบรมลูกค้าองค์กร
    • คอร์สออนไลน์ SkillLane
    • แนะนำวิทยากร
    • Excel/Power BI Skill Map
    • Quiz
  • Shop
    • คอร์สออนไลน์
    • สินค้าทั้งหมด
    • หนังสือเล่ม
    • E-Book
    • Cart
  • Download
    • Download ไฟล์จากเทพเอ็กเซล
    • ThepExcel-Mfx : M Code สำเร็จรูป
    • Date Table สำเร็จรูป
    • กราฟ My Skill
    • github.com/ThepExcel
  • รวม Link
    • รวม Link สอน Excel & Power BI ทั้งไทยและเทศ
    • รวม Link สอน Python / Programming
    • หนังสือแนะนำ
    • Facebook ThepExcel
    • YouTube ThepExcel
    • DAX Formatter
  • Contact
    • แนะนำ เทพเอ็กเซล (Thep Excel)
    • แนะนำวิทยากร : อาจารย์ ศิระ เอกบุตร (ระ)
    • นโยบายการคุ้มครองข้อมูลส่วนบุคคล (Privacy Policy)
  • Facebook
  • YouTube

Excel VBA พื้นฐาน ตอนที่ 3 : การวน Loop

excel-vba-loop

Categories 📂

Excel VBA

Tags 🏷️

for, loop, while

ในที่สุดเราก็มาถึงบทที่จะใช้ความสามารถของการเขียนโปรแกรมกันอย่างเต็มที่กันซักที ซึ่งก็คือความสามารถในการวน Loop นั่นเองครับ เรามาดูกันมามีเรื่องอะไรที่ควรจะต้องรู้บ้าง

สารบัญ

  • การวน Loop คืออะไร?
  • การอ้างอิง Cell ด้วยตัวเลข
    • วิธีการอ้างอิง Cell เดียว
    • ถ้าจะอ้างอิงเป็นช่วง
    • การเลื่อน Cell หรือ Offset ไปทิศต่างๆ
  • For Loop
    • For…Next
    • For Each … Next
    • การประกาศตัวแปรให้ชัดเจน ทำให้เขียน Code ง่ายขึ้น
    • การออกจาก For
  • Do While Loop
  • จริงๆ ยังมี Loop แบบอื่นอีก แต่พอแล้วล่ะ
  • ตัวอย่างการใช้ Loop

การวน Loop คืออะไร?

การวน Loop คือการสั่งให้ Run Code อะไรบางอย่างหลายๆ รอบ ซึ่งแต่ละรอบอาจจะมีอะไรบางอย่างเปลี่ยนไปก็ได้นะ

เช่น ถ้าเราอยากให้ Excel สร้าง Sheet ใหม่ขึ้นมา เราสามารถใช้คำสั่ง Worksheets.Add ได้เลย

และถ้าเราอยากให้ทำแบบนี้ 5 รอบล่ะ?

เราก็ทำแบบนี้ได้

Worksheets.Add
Worksheets.Add
Worksheets.Add
Worksheets.Add
Worksheets.Add

แต่มันไม่เท่เลย เพราะ Maintain แก้ Code ยาก แถมเหนื่อยด้วยถ้าต้องทำเยอะๆ หรือ code เรามีมากกว่า 1 คำสั่ง เป็นต้น

ดังนั้นเราจะใช้การวน Loop มาช่วยก็ได้ครับ จะได้ไม่ต้องเขียนอะไรซ้ำๆ หลายๆ รอบไงล่ะ

การอ้างอิง Cell ด้วยตัวเลข

การจะใช้ Loop ได้ดี เราควรจะรู้จักวิธีการอ้างอิง Cell อีกแบบนึงก่อน ที่ใช้ตัวเลขมาช่วยแทนที่จะเป็นชื่อ นั่นเป็นเพราะเลขทำให้วน Loop ได้ง่ายยังไงล่ะ

วิธีการอ้างอิง Cell เดียว

สามารถใช้ การอ้างอิงด้วย Cells เพื่ออ้างอิง Range ด้วยตัวเลขได้ ในรูปแบบของ Cells(เลขแถว, เลขคอลัมน์)

Tips : เวลา Excel อ้างอิงเลขแถว/เลขคอลัมน์ มักจะอ้างอิงแถวก่อนคอลัมน์เสมอ (Row ก่อน Column) ลองสังเกตดูได้ ไม่ว่าจะใส่สูตร Index, Offset หรือพวก Matrix ก็เป็นแบบนั้น

Cells(3,2).Select

แบบนี้มีค่าเท่ากับ Range(“B3”).Select

ถ้าจะอ้างอิงเป็นช่วง

เราสามารถสามารถใช้ Cells ผสมกับ Range ได้แบบนี้

Range( Cell เริ่มต้น, Cell สิ้นสุด)
Range( Cells(3,2), Cells(5,4)).Select

แบบนี้มีค่าเท่ากับ Range(“B3:D5”).Select

การเลื่อน Cell หรือ Offset ไปทิศต่างๆ

เราสามารถใส่ Property ที่ชื่อว่า Offset เพื่อเลื่อน Range ไปยังทิศต่างๆ ได้ ในรูปแบบของ

Range.Offset(จำนวนแถวที่จะเลื่อน,จำนวนคอลัมน์ที่จะเลื่อน)

เช่น

Range("A1:B3").Offset(4, 2).Select

For Loop

ใน VBA นั้นมี For Loop อยู่ 2 แบบ นั่นก็คือ For… Next กับ For Each เรามาดูทีละตัวกัน

For…Next

มีวิธีการใช้ คือ

For Counter = เลขเริ่ม To เลขจบ
   Code คำสั่งที่จะให้ Run ซ้ำๆ
Next Counter
'Counter จะเป็นตัวแปรชื่ออะไรก็ได้ ปกติชอบใช้ i กัน

เช่น

For i = 1 To 5
   Worksheets.Add
Next i

แบบนี้ก็จะมีการรัน Worksheets.Add จำนวน 5 ครั้ง นั่นเอง

ซึ่งใน Code ที่รัน เรามักจะเอา Counter มาทำอะไรซักอย่างด้วย เช่น ใช้ประกอบกับ Cells(เลขแถว,เลขคอลัมน์) แบบนี้

For i = 1 To 5
   Cells(i, 1) = i * 10
Next i

เมื่อ Run ก็จะได้ผลลัพธ์ดังรูป

  • Loop ที่ 1 i เป็น 1 ก็จะรันคำสั่ง Cells(1,1) = 1*10
  • Loop ที่ 2 i เป็น 2 ก็จะรันคำสั่ง Cells(2,1) = 2*10
  • ….
  • Loop ที่ 5 i เป็น 5 ก็จะรันคำสั่ง Cells(5,1) = 5*10

For Each … Next

สำหรับ For Loop อีกแบบ จะเป็นการวน Loop เท่ากับจำนวนสมาชิกตัวลูกที่อยู่ใน Collection นั้นๆ ในรูปแบบดังนี้

For Each element In collection
   Code คำสั่งที่จะให้ Run ซ้ำๆ
Next element

เช่น

หากเราเลือก Range ไว้หลายช่อง จริงๆ แล้ว Range ที่เลือกก็เป็น Collection ที่ประกอบไปด้วย Range ย่อยๆ หลายๆ อันเหมือนกันนะ

แบบนี้มันจะวน Loop จนครบสมาชิกทุกอันของ Selection ได้เลย ว่าในแต่ละ cell อยู่แถวเลขอะไร โดยที่เราไม่ต้องมานับเองว่ามันมีกี่อัน ซึ่งมีประโยชน์มากๆ ในชีวิตจริง โดยส่วนตัวเป็นรูปแบบ Loop ที่ผมชอบมากที่สุดเลยล่ะ

การประกาศตัวแปรให้ชัดเจน ทำให้เขียน Code ง่ายขึ้น

ถ้าเขียน Code แบบตัวอย่างก่อนหน้า Excel จะยังไม่รู้ว่า c คือ element อะไร ทำให้ไม่มี ToolTips ขึ้นมาช่วย ถ้าให้ดีเราต้องบอกมันนิดนึง ด้วยการประกาศตัวแปร ในรูปแบบว่า

Dim ตัวแปร as ประเภทข้อมูล 

เช่น

Dim c As Range
For Each c In Selection
    c.Value = c.Row
Next c

พอประกาศตัวแปรชัดเจนแล้ว จะทำให้ตัว Tool Tips ขึ้นมาได้อย่างถูกต้องเลย

การออกจาก For

เราสามารถออกจาก For ได้โดยการใช้คำสั่ง Exit For ซึ่งมักใช้ผสมกับคำสั่ง If เช่น

Sub Macro3()
Dim c As Range
For Each c In Selection
    If c.Value > 30 Then
        Exit For
    Else
        c.Font.Color = RGB(255, 0, 0)
    End If
Next c
End Sub

มันก็จะ Loop ไปเรื่อยๆ ที่ละ Range แต่พอไปเจอว่าค่ามากกว่า 30 ก็ออกจาก Loop For ทันที (30 ยังไม่ออก)

Do While Loop

ต่อไปก็เป็น Loop อีกประเภทนึงที่ควรรู้จัก นั่นก็คือ การทำอะไรบางอย่างในขณะที่เงื่อนไขยังคงเป็นจริงอยู่ ในรูปแบบว่า

Do While เงื่อนไข
    Code คำสั่งที่จะให้ Run ซ้ำๆ
Loop

ซึ่งมีการเช็คเงื่อนไขบางอย่างก่อน กรณีที่เงื่อนไขเป็นจริงจะทำ Action ตามที่เรากำหนด แล้วก็กลับไปเช็คเงื่อนไขใหม่อีกครั้ง เช่น

Sub Macro3()
Range("A1").Select
Do While ActiveCell.Value < 35
    ActiveCell.Font.Color = RGB(0, 0, 255)
    ActiveCell.Offset(1, 0).Activate
Loop
End Sub

แบบนี้พอมันเช็คว่าค่าใน A4 (ที่เป็น ActiveCell ใน Loop นั้น) ไม่ได้น้อยกว่า 35 มันก็ออกจาก Loop เลย ไม่ได้เปลี่ยนให้เป็นสีฟ้า

Tips : ส่วนการออกจาก Do While ก็สามารถใช้ Exit Do ได้ครับ

จริงๆ ยังมี Loop แบบอื่นอีก แต่พอแล้วล่ะ

จริงๆ ยังมี Loop แบบอื่นอีก แต่ผมคิดว่าไม่จำเป็นหรอก เราใช้ Loop แค่ 3 แบบนี้ก็เหลือแหล่แล้วครับ
ใน Python ก็มีแค่ For กับ While ยังทำงานได้เลย ^^

ตัวอย่างการใช้ Loop

ลอง Fill สี R G ไล่ 1 ถึง 255 ส่วน B เป็น 0 ไป ลงไปใน Cell แบบสวยงาม

ใน Code จะเห้นว่าเราสามารถใส่ For Loop 2 ชั้นซ้อนกันก็ได้นะ แต่ใช้ Counter คนละตัว ซึ่งผมใช้ r กับ g อย่างละ 255

Sub Macro3()
Range("A1").Select
Application.ScreenUpdating = False

For r = 1 To 255
    For g = 1 To 255
        Cells(r, g).Interior.Color = RGB(r, g, 0)
    Next g
Next r
Application.ScreenUpdating = True
End Sub

Tips : เราใส่ Application.ScreenUpdating = False เพื่อปิดการแสดงผลจนกว่าจะทำเสร็จ ค่อยทำให้เป็น True ไม่งั้นมันจะ Run นานมาก เพราะต้องรันไปแสดงผลไป (การทำแบบนี้จะเร็วขึ้นมากๆ ผมลองแล้วเร็วกว่ากัน 10 เท่า++ ได้)

จะได้ผลลัพธ์แบบนี้ (ผม Zoom Out ออกมาให้ เหลือแค่ 10% นะ แต่ละช่องจะเล็กมากๆ เลย)

ถ้าเปลี่ยนไปรันตัว b แทนก็จะได้อีกสีนึง สวยดีเนอะ 555

แชร์ความรู้ให้เพื่อนๆ ของคุณ
1K    
1K    

ติดตามเทพเอ็กเซล

  • Facebook
  • YouTube

อบรมกับเทพเอ็กเซล

🔥 คอร์สใหม่ล่าสุด 🔥

การทำ Optimization ด้วย Excel Solver
สำหรับงานวางแผน
คอร์สออนไลน์ เทพเอ็กเซล
คอร์สออนไลน์ จากเทพเอ็กเซล ดูกี่รอบก็ได้
อบรม Excel / Power BI ให้องค์กรของคุณ

บทความล่าสุด

  • วิธีสั่ง Prompt และตั้งค่าใน Stable Diffusion ให้รูปสวยโดนใจ [Part3]
  • วิธีเรียกใช้งาน Model เจ๋งๆ ใน Stable Diffusion [ตอนที่2]
  • วิธีใช้งาน AI สร้างรูปสุดเจ๋งและฟรีด้วย Stable Diffusion ฉบับมือใหม่ [ตอนที่1]
  • 10 ไอเดีย เรียนรู้ Excel ผ่าน ChatGPT AI สุดเจ๋ง
  • การทำ Simulation ด้วย Excel
  • แกะเคล็ดวิชา Excel Wizard ในการแข่ง Speed Run Excel ระดับโลก
  • เจาะลึก CALCULATE ใน DAX แบบลึกสุดใจ : Part 2

บทความแนะนำ

🔥ฟังก์ชันทั้งหมดใน Excel 🔥

  • แกะเคล็ดวิชา Excel Wizard ในการแข่ง Speed Run Excel ระดับโลก
  • เจาะลึก CALCULATE ใน DAX แบบลึกสุดใจ : Part 1
  • Series สอนดึงข้อมูลจากเว็บ ด้วย Power Automate Desktop
  • สรุปการใช้ LAMBDA ฟังก์ชันที่ใช้สร้างฟังก์ชันใน Excel 365 และผองเพื่อน
  • วิธีใช้ Excel คำนวณระยะเวลาการทำงานรวม แถมระบุเวลาพักได้แบบยืดหยุ่น
  • วิธีจัดการข้อมูลแย่ๆ ด้วย Power Query ทั้งข้อมูลปนกัน ข้อมูลอยู่บนหัวตาราง
  • แยกข้อมูลที่อยู่สุดเน่า ด้วย Excel Power Query

Categories

Tags

ai collection concepts copy database Data Model data table data validation date dax dropdown error excel filter finance find format formula function game graph IF index intro irr len link logic lookup match m code merge mid overview paste pivot power query row sort speed split substitute table text textjoin time tips trim vba vlookup

Archives

  • March 2023 (2)
  • February 2023 (2)
  • January 2023 (1)
  • October 2022 (1)
  • September 2022 (3)
  • August 2022 (3)
  • July 2022 (1)
  • June 2022 (3)
  • May 2022 (1)
  • April 2022 (2)
  • February 2022 (1)
  • December 2021 (2)
  • November 2021 (10)
  • September 2021 (2)
  • August 2021 (6)
  • July 2021 (2)
  • June 2021 (2)
  • May 2021 (10)
  • April 2021 (3)
  • March 2021 (3)
  • February 2021 (4)
  • January 2021 (8)
  • December 2020 (5)
  • November 2020 (13)
  • October 2020 (5)
  • September 2020 (11)
  • August 2020 (4)
  • July 2020 (13)
  • June 2020 (17)
  • May 2020 (16)
  • April 2020 (16)
  • March 2020 (10)
  • February 2020 (15)
  • January 2020 (16)
  • December 2019 (4)
  • November 2019 (3)
  • October 2019 (9)
  • September 2019 (1)
  • August 2019 (7)
  • June 2019 (3)
  • May 2019 (9)
  • April 2019 (9)
  • March 2019 (2)
  • February 2018 (1)
  • January 2018 (3)
  • November 2017 (3)
  • August 2017 (1)
  • July 2017 (1)
  • June 2017 (1)
  • May 2017 (6)
  • April 2017 (6)
  • March 2017 (7)
  • February 2017 (1)
  • January 2017 (2)
  • December 2016 (1)
  • October 2016 (2)
  • September 2016 (3)
  • August 2016 (2)
  • July 2016 (2)
  • June 2016 (1)
  • May 2016 (1)
  • April 2016 (1)
  • March 2016 (2)
  • February 2016 (1)
  • January 2016 (2)
  • December 2015 (2)
  • November 2015 (5)
  • October 2015 (3)
  • June 2015 (2)
  • May 2015 (1)
  • April 2015 (26)
  • January 2015 (1)
  • December 2014 (1)
  • November 2014 (2)
  • October 2014 (1)
  • September 2014 (2)
  • August 2014 (1)
  • June 2014 (1)
  • May 2014 (1)
  • April 2014 (3)
  • March 2014 (3)
  • February 2014 (12)
  • January 2014 (7)
  • December 2013 (2)
  • November 2013 (8)
  • October 2013 (2)

เทพเอ็กเซล : Thep Excel

copyright © 2022

  • Facebook
  • YouTube
เว็บไซต์นี้ใช้คุกกี้ (Cookies)
บริษัท เทพเอ็กเซล จำกัด ให้ความสำคัญต่อข้อมูลส่วนบุคคลของท่าน เพื่อการพัฒนาและปรับปรุงเว็บไซต์รวมถึงสินค้าและบริการต่างๆ หากท่านใช้บริการเว็บไซต์นี้ โดยไม่มีการปรับตั้งค่าใดๆ แสดงว่าท่านยินยอมที่จะรับคุกกี้บนเว็บไซต์ และนโยบายสิทธิส่วนบุคคลของเรา
ตั้งค่าคุกกี้ยอมรับทั้งหมดอ่านเพิ่มเติม
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT