Automatically translated.View original post

🔻 Auto Adapt Excel Column with View Code (VBA)

2025/12/21 Edited to

... Read moreถ้าใครเริ่มหัดใช้ VBA ใน Excel แล้วเจอปัญหา “คอลัมน์กว้างไม่พอดี” โดยเฉพาะไฟล์ที่มีหัวตารางอย่าง วันที่, รายชื่อลูกค้า, รายการสินค้า, จำนวน, ราคา พอมีข้อมูลยาวๆ เข้ามาทีไรต้องมานั่งดับเบิลคลิกปรับความกว้างตลอด บอกเลยว่าแก้ด้วย VBA ได้ง่ายมาก และเป็นงานอัตโนมัติที่คุ้มสุดๆ แนวคิดของโค้ดนี้คือให้ Excel “ปรับคอลัมน์ให้พอดีกับข้อความ” ทุกครั้งที่เราเข้าไปที่ชีทนั้น (Activate) ทำให้เปิดชีทเมื่อไหร่ ตารางจะดูเรียบร้อยทันที ไม่ต้องกด AutoFit เอง วิธีใช้งาน (ทำครั้งเดียวแล้วจบ) 1) ไปที่แท็บชีทด้านล่าง (เช่น Sheet1) แล้วคลิกขวา 2) เลือก View Code 3) จะเปิดหน้าต่าง Microsoft Visual Basic for Applications ขึ้นมา ให้เลือกออบเจ็กต์ของชีทนั้น 4) วางโค้ดในช่องว่างของชีท: Private Sub Worksheet_Activate() Columns.AutoFit End Sub ทิปที่ผมใช้จริงแล้วช่วยมาก - ถ้าชีทมีหลายตารางและไม่อยากให้ทั้งชีท AutoFit ทั้งหมด (บางทีทำให้คอลัมน์แคบ/กว้างเกิน) ให้จำกัดช่วงคอลัมน์ เช่น A:E Private Sub Worksheet_Activate() Columns("A:E").AutoFit End Sub - ถ้ามีคอลัมน์ “ราคา/จำนวน” ที่อยากให้คงความกว้างเท่าๆ กัน ไม่อยากให้ AutoFit แล้วแกว่งไปมา ให้ AutoFit เฉพาะคอลัมน์ข้อความ เช่น B:D แล้วล็อกคอลัมน์ตัวเลขไว้ Private Sub Worksheet_Activate() Columns("B:D").AutoFit Columns("E:F").ColumnWidth = 12 End Sub ข้อควรระวังเล็กน้อย - ไฟล์ต้องบันทึกเป็น .xlsm (Macro-Enabled) ไม่งั้นโค้ดจะไม่ทำงาน - ถ้าข้อมูลในชีทเยอะมากๆ การ AutoFit ทุกครั้งที่เข้าอาจหน่วงนิดนึง แนะนำจำกัดช่วงคอลัมน์ที่จำเป็น - ถ้าเปิดไฟล์แล้ว Macro ถูกปิด (Disable) โค้ดจะไม่รัน ต้องกด Enable Content ก่อน โดยรวมถือเป็น VBA ใน Excel ที่เหมาะกับมือใหม่มาก เพราะสั้น เข้าใจง่าย และเห็นผลทันที โดยเฉพาะงานตารางขาย/สต็อก/รายชื่อลูกค้า ที่ข้อมูลเปลี่ยนทุกวัน

Related posts

A tablet displays an Excel wedding budget spreadsheet on a desk with notes and a planner. The image is titled 'Stop Struggling with Excel Learn These Super Easy Formulas'.
This image details core Excel calculation formulas: SUM, AVERAGE, MIN, and MAX. Each function is explained with an example Excel table showing its application and purpose.
This image explains Excel's reference formulas, VLOOKUP and HLOOKUP. It provides examples with tables demonstrating how to search and retrieve data vertically and horizontally, along with usage tips.
Excel shortcuts every student should know! 👩🏻‍💻
Stop Wasting Time: Master These Excel Formulas for Maximum Efficiency! 🕒 If you’ve ever struggled with Excel, mastering formulas can seriously up your game. Here’s a breakdown of the essentials that’ll make you look like a pro 1.Core Calculation Formulas 🧮 These are the basics you can’t live
emilie.studygram

emilie.studygram

1184 likes

A vibrant graphic titled 'USEFUL EXCEL FORMULAS' in green, overlaid on a spreadsheet displaying various charts, data tables, and financial figures. The image includes 'Career | Lemon 8' branding and a 'SWIPE' indicator.
A laptop screen showing code, with a text box explaining the 'VLOOKUP' Excel formula. It defines its function for searching large datasets and provides a detailed example. The image is branded 'Career | Lemon 8 | Yun Jung'.
A text box on a wooden desk with a laptop, smartphone, and coffee cup, explaining 'SUMIF & SUMIFS' Excel formulas. It defines their use for adding cells based on conditions and provides a SUMIF example. The image is branded 'Career | Lemon 8 | Yun Jung'.
Useful Excel Formulas to save your time at work!
Hey everyone! Excel formulas are awesome for speeding up calculations and analyzing data. They range from simple math stuff to more complex tasks like searching and matching data. Learning these formulas can make your work easier and help you get more done in less time. Try out online tutorials and
Yun Jung

Yun Jung

872 likes

100 Excel Tips
100 Excel Tips The best Shortcuts, Formulas, Formatting & Advanced Tips Bookmark this, you'll save 1,000 of hours! A list of tips that all professionals need. Here is a preview: ⌨️ Shortcuts 1. How to hide a column? Ctrl + 0 2. How to hide a row? Ctrl + 9 3. How to
ExpressoSolut

ExpressoSolut

1441 likes

Excel vs Word
Excel formatting does the same thing as many people using Word #tutorial #exceltips #exceltricks #exceltutorial #exceltraining #worktips #alwayslearning
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

4948 likes

A woman takes a mirror selfie, holding a coffee cup and phone, with text overlay 'EXCEL SHORT CUTS SAVE TIME & FRUSTRATION PART 1'. Abstract shapes frame the image.
A beige graphic slide explains the Excel shortcut 'SHIFT + END + DOWN' for selecting an entire column or section of data, with a 'SWIPE' indicator.
A brown graphic slide details the Excel shortcut 'CTRL + A' which selects all data in a worksheet, accompanied by a 'SWIPE' instruction.
EXCEL SHORTCUTS
These excel short-cuts are just a few that have made my excel work take a fraction of the time and genuinely changed my work life!! Working in excel can be extremely frustrating when not using the tool efficiently. Here are some crucial shortcuts to enhance your experience with Excel. CTRL + A
Peyton’s Place

Peyton’s Place

2583 likes

A brown note card with 'Best study HABITS to adapt' written on it, placed over a background of handwritten study notes on a grid paper.
A close-up of a planner showing a 'TO DO' list with checked tasks, emphasizing the importance of 'Consistency' in study habits.
A desk setup with a laptop displaying historical text about colonial trade and a notebook with handwritten notes, illustrating 'Active engagement' in studying.
5 study habits to adapt!
Here are five of the best study habits to adopt: 1. Consistency Regular, consistent study sessions over time are more effective than cramming. Set aside dedicated time each day or week for studying. 2. Active engagement Actively engage with the material by summarizing, asking questions
essynotes

essynotes

268 likes

ANALYZE DATA - EXCEL TOOL
Excel's Analyze Data Tool is a game-changer, simplifying the way you work with data. Say goodbye to the days of laboriously creating tables and charts and struggling with formatting intricacies. This tool automates the process, making data analysis and visualization effortless. With just a f
Peyton’s Place

Peyton’s Place

252 likes

This image displays a Microsoft Excel Cheat Sheet covering basic skills, including the program screen, keyboard shortcuts, navigation, and formatting. It features a 'Swipe' overlay, indicating more content is available.
This image shows a Microsoft Excel Cheat Sheet focused on advanced skills, specifically detailing PivotTable elements, fields, layout, and charts. It provides a comprehensive guide to using PivotTables in Excel.
This image features a profile page with the text 'GET FULL PDF VERSION FROM MY WEBSITE' and an arrow pointing to 'valder.org'. It also displays user statistics for 'Valder', an AI expert and independent developer.
How to get the excel Cheatsheet pdf?
I just made my own website : valder.org A lot of free data resources will share on it. If you are a student in college you can follow to get more.
Valder

Valder

60 likes

Copy paste unique only in excel trick
Copy just the unique values in excel #exceltraining #exceltips #exceltricks #tutorials #excelforbeginners
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

13 likes

Count in excel
Count the number of times an item appears in a column or list in excel #tutorial #exceltricks #excel #exceltips #exceltraining #fyp #onthisday
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

32 likes

A monitor displays a data visualization tool, Graphy, showing a line and bar chart. The interface offers customization for colors, themes, and fonts, turning data into beautiful charts. The screen is set on a clean desk with a keyboard and plant.
The image highlights the data visualization tool's interface, focusing on color and theme customization. Options include light/dark modes, various color palettes like Monochrome and Colorful, and chart appearance settings to create stunning visuals from data.
This image shows the data visualization tool's chart type selection panel, offering options such as Column, Bar, Line, Pie, and Heatmap. It also displays settings for bar chart appearance and style, enabling diverse data visualization.
Website to Turn Data into Beautiful Graphs Charts
Spreadsheets can be confusing, but your data doesn’t have to be. With Graphy, you can turn numbers into clear, beautiful charts in just a few clicks.  No complex Excel formulas, no stress, just easy customization and effortless sharing.  Whether it’s for work, school, or personal projects, ma
Reverelia

Reverelia

46 likes

how i study for my finals as a college student ✏️
it is finals week at my school and i have started studying for mine that are next week. i have one that is in ancient roman history that i have been dedicating my time to prepare for. some of my favorite study methods are to: ✏️rewrite notes until you remember them ✏️use quizlet to make study gui
ella🤍

ella🤍

66 likes

Habits to adapt in 2025
Ready to level up? These habits will not only change, but also transform your life! Which habits will you adapt in 2025? Bonus habit: Let go of habits and emotions that don't align with the person you are becoming! Don't forget to like, comment, save for later and share with a
Ruth Noemi 💛

Ruth Noemi 💛

269 likes

An outdoor dining scene with people seated at tables, featuring the overlaid text "Freeze the Top Row in Excel." A purple glass is visible in the foreground on a black mesh table.
A light beige background with black text asking, "Do you ever have hundreds of rows of data and when scrolling down, you loose sight of the column header and forget which column/field is which?"
A light beige background with black text stating, "This is when freezing your top row is crucial! I will show you how!"
HOW I FREEZE THE TOP ROW IN EXCEL
The ability to freeze that first row of my column headers has been a lifesaver, allowing me to scroll through thousands of rows of data without losing sight of my column headers/fields. By simply selecting the row below the one you want to freeze, heading to the "View" tab, and clicking
Peyton’s Place

Peyton’s Place

105 likes

A desk with a keyboard, mouse, and a plant in front of a window with blinds. Text overlay reads 'WRITING Story Outline STEP BY STEP' and 'lemon8 @charinataylorauthor'.
A tablet displays an Excel spreadsheet with story outline data. An overlay defines 'POV' as the character's perspective for a chapter, explaining it avoids confusion and delivers correct information.
A tablet displays an Excel spreadsheet with story outline data. An overlay defines 'Beats' as small story moments making up a scene, ensuring the story moves forward without 'fillers'.
How I Map Out My Story Outline 📊👩🏽‍💻✍🏽
When I was creating my story, I was all over the place because so many ideas were in my head. I eventually started writing the chapters down and the scenes in those chapters to make my story form. Why Excel? • I was able to list my categories easily through each column on excel. • It helpe
Charina Taylor Studio

Charina Taylor Studio

465 likes

Self-Knowledge Tools Compared — One Actually Adapt
I’ve spent years collecting personality reports, from MBTI and DISC to every astrology app under the sun. My shelves are basically a museum of self-discovery tools, and I’m not skeptical at all—I’ve genuinely learned something valuable from each one. ☀️ I’ve always been a bit of a self-knowledge ne
Thannya A.

Thannya A.

0 likes

🐠 ADAPT TO SURVIVE
Nature teaches a powerful lesson: survival isn’t about strength alone. It’s about adapting when life changes. The people who grow the most are often the ones who learn to adjust the fastest. #LifeRulers #AdaptAndGrow #NatureWisdom #MindsetMatters #RuleYourLife
Life Rulers 👑

Life Rulers 👑

11 likes

An overhead view of a desk with papers, a laptop, a phone displaying a calculator, and stacks of money, with a prominent Excel 'S' logo and text overlay 'Steps for Learning Excel for Beginners'.
A green and white graphic titled 'Master Simple Excel Operations', listing five basic Excel tasks: creating a workbook, entering data, adjusting column/row size, inserting/deleting cells, and using functions.
A graphic titled 'Keyboard Function Key Identification' showing a white keyboard layout and a table identifying common keys like Esc, Tab, Caps Lock, Shift, Ctrl, Alt, Enter, Backspace, Sleep, and Wake Up.
Getting Started with Excel: It's Really Simple!
We'll start with the basics, learning about Excel's interface, toolbar, cells, and other fundamental operations. Then, we'll move on to common office shortcuts, as well as some frequently used functions and formulas. #ExcelBasics #ProductivityTips #SpreadsheetSkills #Exce
WPS Office

WPS Office

40 likes

Excel cheat sheet
Excel cheat sheet #excel #exceltips #exceltricks #exceltraining #tutorials #excel_learning
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

14 likes

#IHIP News: Trump in FULL MELTDOWN After Warnings of WORST Economic CRASH in HISTORY!
Neva Lena

Neva Lena

40 likes

Excel time stamps
Yes, I said permanent time stamps #exceltips #excel #tutorial #worktips #exceltraining #exceltricks
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

54 likes

HOW I CREATE SPARK-LINES IN EXCEL
What is a sparkline? A sparkline is a small, simple, data-intense graphical representation typically used in line with text to show trends, variations, or patterns in data at a glance. Creating a sparkline in excel is pretty simple. I highlight a range of horizontally organized data and go into
Peyton’s Place

Peyton’s Place

319 likes

Create a Scrolling Data List in Excel Like a Pro💡
✨ Welcome to Our Excel Mini-Class! ✨ Hey, Excel lovers! 🙌 Want to take your spreadsheets to the next level? It’s time to create a scrolling data list—an easy way to manage long data entries without cluttering your sheet!📝💼 Why use a scrolling list? 💫 Save space: Keep your data organized and
WPS Office

WPS Office

1 like

Excel percent format issue trick
Excel percent format issue trick. Fix percentage issues. #tutorial #exceltips #excel #excelpro #exceltricks #exceltutorial #exceltraining
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

11 likes

Be like water, adapt and overcome #adapt #overcome
#CapCut Be like water, adapt and overcome #adapt #overcome
codysantor

codysantor

147 likes

A comprehensive guide titled 'How to Use Copilot,' detailing its key features across Excel, Word, and PowerPoint, along with specific prompt examples for each application.
How to Use CoPilot
#copilot #copilotinword #copilotinexcel
LouiseAnn1960

LouiseAnn1960

124 likes

#excel #exceltips #technology #miami
#technologyineducation #excel #teacher #computer #office
Aprende Excel y Tech Facil

Aprende Excel y Tech Facil

1 like

Excel dot trick
Do you know the DOT?? Excel trick using the dot to remove extra zeroes #exceltraining #excel #exceltricks #exceltraining #exceltutorial #business #businesstips
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

104 likes

Subject 3, Day 23: Be Ready to Adapt.
Change is inevitable, be ready to tackle it and accept that you cannot do the same thing forever to achieve success. #life #lesson #learn
Keith Hurly

Keith Hurly

0 likes

Excel Guide
#excelspreadsheets #
FWSbeautybar

FWSbeautybar

6 likes

Erase Blank Lines in Excel in a Flash! ⚡📊
✨ Welcome to Our Excel Mini-Class! ✨ Ever end up with a ton of blank rows in your Excel sheet and wonder how to get rid of them fast? 🙄 Well, I’ve got a super quick solution for you! Let’s clean up your spreadsheet in just a few clicks! 🧹✨ With the tutorial in the video, your sheet will be cl
WPS Office

WPS Office

1 like

Adapt and overcome
Always adapt to your surroundings. #uplifting #positiveenergy #adapt
🤪Tha_Joker🤪

🤪Tha_Joker🤪

3 likes

ADAPT AND CONQUER
ADAPT TO LIFE CHANGES DIFFERENT ROUTE DOESN'T MEAN THE GOAL HAS CHANGED. . . . #goalsetting #objective #contentcreator #lifehappens #makingchangehappen
JamaicanQueen🇯🇲🇺🇸

JamaicanQueen🇯🇲🇺🇸

2 likes

Must-Know Excel Tip for Busy Days! ⏰ 🥰
✨ Welcome to Our Excel Mini-Class! 📈 In this session, we’re unveiling the magic of Text to Columns! 🤓 Have you ever had a long list of data all in one cell and wished you could separate it into neat, organized columns? Well, now you can—with just a few clicks! 🔥 No more messy data or manual cutt
WPS Office

WPS Office

4 likes

Excel automatic sort
Automatically sort spreadsheet as you type #tutorials #excel #friday #exceltips #exceltraining
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

12 likes

How to Create an Email ID using CONCAT in Excel
How to Create an Email ID using CONCAT Function in Excel #exceltraining #exceltricks #exceltutorial #excelsheets #msexcel
DataUnleash

DataUnleash

1 like

Track hours worked using excel
#excel #tutorial #exceltricks #excelshortcuts #excelmastery
Excel tips at XecuteTheVision

Excel tips at XecuteTheVision

9 likes

Garrote cars broker

Garrote cars broker

1 like

Excel Hacks: 4 Quick Ways to Fill Serial!
📈 Welcome to Our Excel Mini-Class! 💫 In this session, we're unveiling the magic of fill serial! Ready to save time on your Excel spreadsheets? Here's 4 super fast ways to fill serial numbers like a pro! 💼✨ Get ready to level up your Excel skills! 🙌 #wps #fillserial #exceltips
WPS Office

WPS Office

7 likes

See more