Showing posts with label How To. Show all posts
Showing posts with label How To. Show all posts

Wednesday, September 25, 2024

Generate A Random Number In Google Sheets

I was thinking about trying to transfer one of my most popular spreadsheet templates, Super Bowl Squares, from Excel to Google sheets. However, macros do not work in Google sheets. I was thinking about trying to recreate at least some of them, and the first problem to solve was how to make a random number generator script in Google Sheets.

Here's how you can create a Google Apps Script to generate random numbers between 0 and 9 in cells A1 to A9 without any repeats. 

Steps to Create the Google Apps Script:

  1. Open your Google Sheet.
  2. Click on Extensions in the menu.
  3. Select Apps Script.
  4. Delete any existing code in the script editor, and paste the following code:

function generateRandomNumbers() { // Create an array with numbers 0 to 9 var numbers = Array.from({length: 10}, (_, i) => i); // Shuffle the array for (var i = numbers.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; } // Get the active spreadsheet and sheet var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // Place the shuffled numbers in cells A1 to A9 for (var k = 0; k < 9; k++) { sheet.getRange(k + 1, 1).setValue(numbers[k]); } }
  1. Save the script by clicking the disk icon or pressing Ctrl + S. You can name it something like RandomNumberGenerator.
  2. Close the Apps Script editor.
  3. Back in your Google Sheet, go to Extensions -> Macros -> Import and then select your generateRandomNumbers function.
RandomNumberGenerator google apps script


How to Run the Random Number Generator Script:

  • To run the script, go to Extensions -> Macros -> generateRandomNumbers.
  • The script will place random numbers between 0 and 9 in cells A1 to A9, with no repeats.

If this is your first time running the script, Google Sheets may ask you for permission to run the script. Approve the permissions to proceed. 

In my templates, I make macros easy to use by running them from a button click. Yes, you can run the script from a button in Google Sheets too! Here’s how you can set it up:

Step 1: Create the Script

  1. Open your Google Sheet.
  2. Click on Extensions in the menu.
  3. Select Apps Script.
  4. Delete any existing code in the script editor, and paste the script provided above.
  5. Save the script by clicking the disk icon or pressing Ctrl + S.

Step 2: Add a Button to Google Sheets

  1. Insert a Drawing (for the Button):

    • Go to your Google Sheet.
    • Click on Insert -> Drawing.
    • Click on the Text Box icon in the Drawing toolbar and draw a text box.
    • Type in a label for your button, such as "Generate Numbers."
    • Format the text and shape as you like.
    • Click Save and Close. The button will now appear on your sheet.
  2. Assign the Script to the Button:

    • Click on the drawing (the button) you just created.
    • Click on the three vertical dots in the top right corner of the button, and select Assign script.
    • In the text box that appears, type the name of your script function, which is generateRandomNumbersInRow.
    • Click OK.

Step 3: Use the Button

  • Now, whenever you click the button, the generateRandomNumbersInRow script will run, and random numbers will be placed in the cells G3 to P3.

This provides a user-friendly way to trigger the script without needing to go through the menu every time. The first problem is solved! Onto the next one...

Sunday, January 8, 2023

Using OpenAI's ChatGPT to Update My Year in Pixels Excel Template

I've been seeing more and more videos on TikTok about this mysterious new artificial intelligence program called ChatGPT. People are saying it will eventually replace Google search. But what really got my attention was a demonstration of ChatGPT writing VBA macros for Microsoft Excel. Now I knew I had to try it for myself. 

I made a Year in Pixels Excel template to track my daily mood back in 2018 but haven't updated it lately. Since it's the start of a new year, I recently received some new comments and questions about how to use and modify the spreadsheet so I figured now would be a great time to update it and add a few new features. Then I had an idea - why don't I use this opportunity to update my mood tracking Excel template to try out ChatGPT? Let's give it a go!


How to have cell fill color conditional formatting change based on the color of another cell?

The request from a user that got me thinking was "how to easily change the colors in my year in pixels sheet?" An experienced Excel user could probably ascertain the colors are applied by conditional formatting formula rules. However, for users who are not Excel savvy, it's not very obvious and there should be an easier way to change the colors. As far as I know, there is none, or at least no easy way in my current version of Excel, to have the fill color in the conditional formatting reference another cell's color. So instead, I will have a macro update the conditional formatting rules at the click of a button. Let's jump over to ChatGPT.

How does ChatGPT work?

Here's the answer after asking it directly: 

GPT (Generative Pre-trained Transformer) is a type of language model developed by OpenAI that uses a transformer neural network architecture to generate text. GPT is trained on a large dataset of text and uses this training to generate new text that is similar in style and content to the training data.

ChatGPT is a variant of GPT that has been fine-tuned on a specific task, such as having conversations with humans. To fine-tune GPT for this task, ChatGPT is trained on a large dataset of conversation data and learns to predict the next word in a conversation based on the words that came before it.

When you input a message to ChatGPT, it processes the message and uses its knowledge of language and conversation patterns to generate a response. It does this by predicting the next word in the conversation based on the input it has received and the context of the conversation so far. The output of ChatGPT is then a response that is generated based on this prediction.

One thing to keep in mind right off the bat: ChatGPT is not always right. It says it right there on the main page under limitations: may occasionally generate incorrect information; may occasionally produce harmful instructions.
For example, I asked "list the ten tallest roller coasters in the world" which should be fairly easy and instead it produces a list that is incorrect and doesn't even make sense.


Not a great start but let's see how it does creating a macro from scratch.

Creating Custom VBA Macros Automatically with ChatGPT

I wasn't sure how specific I needed to be so I decided to err on the side of caution, plus I thought the more detailed I am the less modification I'll probably need to do later. Now I ask ChatGPT: "create a vba macro to make a new conditional formatting rule where range is C4 to N34, if cell value = 5 then change the fill color to the same color as in cell P12." Then it began typing and my jaw dropped.

I copied and pasted the code into Excel VBA editor and it worked! One thing I forgot is this macro will just add new rules applied to the same range. I need to delete all the existing formatting rules before adding new ones, so I ask ChapGPT:


I added the above code to the earlier response and linked it to a newly added button on my sheet. Now a user can change the fill color of a cell, click the button, and the fill colors update automatically to match.

If you want to see all this play out in real time, watch the video I recorded below:

Thoughts on the Future of ChatGPT

It's awesome that it doesn't just spit out the code, but it also suggests how you might need to modify it AND tells you how to run the macro as well. Even though I've only asked it to make simple macros, I already see how this program could save a lot of time.

I'm not done experimenting but so far ChatGPT seems like a much better option over Recoding macros or Google searches that might take you a few tries to find exactly what you're looking for. Especially when you can get custom code on the fly. On one hand, I feel a little obsolete, but on the other I also don't think ChatGPT will completely be replacing programmers just yet as you can see I still had to understand the code and modify it to fit my exact needs.


Download my Year in Pixels template for free here and try it for yourself. Open the macro editor to view the final codes written by ChatGPT.

Tuesday, June 21, 2022

How to change relative hyperlink to exact link in Excel

You may have used the HYPERLINK function in Excel before but what you may not have released is your links can be either relative or absolute (or sometimes called exact or specific). What does this even mean? And how do you change from relative to exact?

Monday, March 28, 2022

Free Meeting Scheduling Excel Template

How often do you ask friends, family, or coworkers which day is the best to get together? Whether it’s a meeting, party, trip, or some other occasion I find myself in these situations all the time. There are several apps and online calendars available to help you coordinate which day works for everyone involved. I used to use a site called Doodle all the time.  The problem with these services is they are not always free, they’re constantly changing and you have to keep relearning how to use them, you have to make an online account, and so on. So I did what I always do – I decided to make an Excel template to determine which day works best for meetings and events!

I used a lot of the same concepts and macro code from my Super Bowl Squares spreadsheet. When you first open the spreadsheet you are greeted by a simple, clean setup page. Here you’ll manually input the number of participants, meeting subject and description.

Next, you’ll enter the start and end dates of the days you want the participants to choose from. It’s very important that these two cells ONLY contain dates. To restrict a user to only being able to enter a date in a cell, go to Data > Data Validation. Under Allow select Date. Be sure to enter a custom error message so if a user makes a mistake they understand what needs to be entered.

When the user clicks Generate Schedule the Schedule sheet is unhidden. The schedule can handle up to 100 participants and up to 365 days. However, you probably won’t need all that so the macro will automatically hide all the rows and columns not needed to make it easy for the user to input their information.


A lot of good Excel tips can be gleaned from examining the event timing spreadsheet. Here's a quick summary of what can be learned by dissecting this free Excel template:
  • How to add and use Option buttons
  • How to use data validation to restrict entry in a cell to a date
  • How to use data validation to restrict entry in a cell to an email address
  • How to get the day of the week from a date
  • How to use command buttons and assign specific macros to them
  • How to send emails from Excel with hyperlinks
  • How to use a formula to show only weekends in Excel
  • How to use conditional formatting to change cell color based on cell value
  • How to hide command buttons by macro
Download the Meeting Scheduler Template here.

Watch How to Coordinate Meetings with Excel

If you want to see how this spreadsheet works and some tips like how to limit a cell where a user can only input a date then watch the video below:


Try it out and let me know if you think it’s a legitimate replacement for Doodle, Calendly or whatever meeting scheduling apps you currently use. 

Thursday, January 6, 2022

How to Add an Excel Shape to Outlook Mail by VBA

Two spreadsheets I am most proud of are my Super Bowl SquaresGame Generator and my College Football Bowl Prediction Pool Manager (Bowl Pick’em Game). I’ve put a lot of time and features into these free templates. However, I still get many requests to add even more features. One of the most asked questions is “how can I share the leaderboard results when all the players aren’t connected to the same network?” I would normally respond with how I do it: “I take a screenshot of the scoreboard and manually email it to the players.” Then it dawned on me – why not automate this process to make it easy for everyone to use? Why not automatically add a picture of the Excel sheet into an email?

There are two methods I can think of off the top of my head for attaching an image into an email with a macro, and here are the pros and cons of each:

  1. The picture is saved on your PC (or needs to be saved by the macro before inserting into the email)  – but either way you have to know the location of the file.
  2. Copy and paste an image already in your spreadsheet into an email. Does not require saving the image. But you must know the shape name so the macro can find it.

For today’s tutorial, I am going to show you how to use the #2 method. 

A thread on method #1 can be found here: https://stackoverflow.com/questions/44869790/embed-picture-in-outlook-mail-body-excel-vba

You can read along or scroll down to watch the video below. Again, for this method to insert an image from a spreadsheet into an email, the image must already be created and named manually so the macro knows what image within the sheet to use.

Name the Shape or Image You Want to Copy and Paste From Excel into Email

First, I need to have a linked image in my spreadsheet that will be copied to the email. Highlight the area (the cells) that you want to have an image of, in my example the scoreboard of my Super Bowl Squares sheet. Next, I created a new sheet within my workbook where I will collect the emails of all the players. I right click, paste special, linked picture. Select the image. Under page layout go to Selection Pane. Rename the picture “Preview1” or some other descriptive name. This is what the macro will use to identify which picture to attach to the email.

I also want to allow the user the option to include a hyperlink to the Excel workbook in the email or not. To do this, I create a checkbox in Excel by going to the developer tab, insert, ActiveX controls, Check Box.

 

How to Add an Excel Shape to Outlook Mail by VBA

Attach Image to Email Excel Macro Code

Now it’s time to write the VBA macro that will automatically send an email to all the players with a picture of the latest scoreboard – all at the click of a button!

I’ve previously shared how to send an email from an Excel sheet but this is my first time attaching an image. Below is the full code with my comments explaining what is happening along the way.

Sub SendEmailUpdate()

'Optimize Macro Speed

  Application.ScreenUpdating = False

  Application.EnableEvents = False

  Application.Calculation = xlCalculationManual

 

'define the workbook, location, and name

Dim Wb1 As Workbook

Set Wb1 = ThisWorkbook

 

Dim OwnerName As String

OwnerName = Application.UserName

 

Dim FileLoc As String

FileLoc = Wb1.FullName

 

Dim WorkbookName As String

WorkbookName = Wb1.Name

 

'SendEmailTo will count the number of people who the email will be sent to

Dim SendEmailTo As Integer

SendEmailTo = 0

 

'we will store all the email addresses in one long string then insert them into the TO line of the email later

Dim ToPerson As String

ToPerson = ""

 

'loop through all players in column A of the Send Scoreboard sheet (up to 100 players max)

Dim x As Integer

For x = 2 To 101

 

    ' get the emails to fill in the TO line

    If Not IsEmpty(Wb1.Worksheets("Send Scoreboard").Range("A" & x).Value) Then

    ToPerson = Wb1.Worksheets("Send Scoreboard").Range("A" & x) & "; " & ToPerson

    SendEmailTo = SendEmailTo + 1

    Else

    'MsgBox "email is blank"

    'NoSEnd = NoSEnd + 1

    End If

   

    ' get the emails to fill in the CC line

    'If Not IsEmpty(WB3.Worksheets(1).Range(CCCol & PICRow).Value) Then

    'CCPerson = WB3.Worksheets(1).Range("D" & PICRow) & "; " & CCPerson

    'CCEmail = CCEmail + 1

    'Else

    'End If

 

Next

 

MsgBox "Email will be sent to " & SendEmailTo & " recipients."

 

how to send email from excel

'get the named Image to attach to the email and copy it

Set oPreview = Wb1.Worksheets("Send Scoreboard").Shapes("Preview1")

oPreview.CopyPicture ' oPreview is now in Clipboard

 

'launch Outlook

    Dim xOutApp As Object

    Dim xOutMail As Object

    Dim xMailBody As String

  

    On Error Resume Next

   

    Set xOutApp = CreateObject("Outlook.Application")

    Set xOutMail = xOutApp.CreateItem(0)

  

'for html email

 

If Wb1.Worksheets("Send Scoreboard").CheckBox1.Value = True Then

    'include the link to the spreadsheet

    xMailBody = "Hello everyone! <br><br>" & "The SuperBowl Squares scoreboard has been updated. You can access the sheet by clicking the link below. <br><br>" & _

    "Link: <br><br>" & "<a href=" & Chr(34) & FileLoc & Chr(34) & " > " & WorkbookName & " </a> " & "<br><br>" & _

    "Thanks for playing," & "<br><br>" & OwnerName

Else

    'false, no link

    xMailBody = "Hello everyone! <br><br>" & "The SuperBowl Squares scoreboard has been updated. Please see the below image: <br><br>" & _

    "Thanks for playing," & "<br><br>" & OwnerName

End If

 

 

    On Error Resume Next

   

    With xOutMail

        .To = ToPerson

        '.CC = CCPerson

        .BCC = ""

        .Subject = WorkbookName

        '.Body = xMailBody

        .HTMLBody = xMailBody

        .Display   'or use .Send

 Quick Note: To use the clipboard to copy and paste the picture into email, you need an Outlook mail editor which can deal with the clipboard. Here I use WordEditor for example. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which represents the Body of your email: https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/dd492012(v=office.12)?redirectedfrom=MSD

       

        Set oInspector = .GetInspector

        Set oWdDoc = oInspector.WordEditor

   

        Set oWdContent = oWdDoc.Content

        Set oWdRng = oWdDoc.Paragraphs(1).Range

        'oWdRng.InsertBefore "This is a test"

        oWdRng.InsertParagraphAfter

        oWdRng.InsertParagraphAfter

 

        Set oWdRng = oWdDoc.Paragraphs(3).Range

        oWdRng.Paste ' paste from oPreview Clipboard

 

        olFormatHTML = 2

        .BodyFormat = olFormatHTML ' change to HTML

       

    End With

   

    On Error GoTo 0

   

    Set xOutMail = Nothing

    Set xOutApp = Nothing

'---------------------------------------------------------------

ResetSettings:

  'Reset Macro Optimization Settings

    Application.EnableEvents = True

    Application.Calculation = xlCalculationAutomatic

    Application.ScreenUpdating = True

End Sub

Thursday, November 18, 2021

Gift Guide for Excel Users 2021

 The 2021 holiday season is officially upon us here in the United States which means it’s time for my annual gift giving guide. I used to panic every year whenever my spouse, parents, and siblings asked me what I wanted for Christmas. I needed to give them an idea otherwise I’d end up with an ugly sweater or some random gadget I would never use.

So to help alleviate some of my stress I started compiling my own holiday gift guide. It’s kind of like the big toy catalog you used to get as a kid, only this is for adults. I’ve made a list of items I think would be very useful or exciting for your fellow Excel users, sorted by different categories (and yes, this post does contain Amazon affiliate links). Some of these items I already use on a daily basis and others are things that are on my own personal wish list. It's my biggest and best gift guide yet! Enjoy!

Monday, June 21, 2021

How to Add Conditional Formatting with a Macro

Conditional Formatting is a useful tool in Excel that allows you to do things like highlight duplicate cells, or color every other row in with color, and so on. If you have a large range or table with many conditional formatting rules, sometimes things can get a little messy. If you’re inserting, adding, or deleting rows and columns often, your conditional formatting rules might go from a short, highly understandable list, to a complete cluster:


One way to be able to reset your conditional formatting rules is with a macro. We’re going to use a macro to automatically delete the conditional formatting and then add it back.

First, to clear and delete all the conditional formatting from a sheet with a macro, use this code, changing the A:AQ with whatever range you’re using:

    '--------delete the conditional formatting--------

With ActiveSheet.Range("A:AQ")

    .FormatConditions.Delete

End With

Now it’s time to add conditional formatting with a macro. In this example, I have a status column C where I enter values, and based on these values the format of my range will change.

Use LastRow to find the last row of data, making it a dynamic range (meaning the size of the range changes based on how much data is inside the range).

'define the last row

LastRow = Cells(Rows.Count, 1).End(xlUp).Row

First, define the range where you want to apply the formatting.

Next, define the formula or rule. Here, I want if the value in Column C is the letter N to change the font color to red. I use double quotations to have a quotation. Notice there is only one $ sign. If I put $C$11 then the formula would not trickle down through the rest of the range.

Finally, define the condition, font color to red the color index is 3. See the font color index here: https://www.automateexcel.com/excel-formatting/color-reference-for-color-index/

This is the first rule I am adding so notice the (1) inside the parenthesis.

'-------add the conditional formatting-------

'if new, change font to red

  With ActiveSheet.Range("D11:AP" & LastRow)

     .FormatConditions.Add Type:=xlExpression, Formula1:="=$C11=""N"""

     .FormatConditions(1).Font.ColorIndex = 3

End With

 

Now I want to add another conditional formatting rule programmatically. This time, change the font color to green if there is an H in the column C. Green uses a 4 in the color index. This is the 2nd rule so notice the (2).

 

'if h, change font to green

  With ActiveSheet.Range("D11:AP" & LastRow)

     .FormatConditions.Add Type:=xlExpression, Formula1:="=$C11=""h"""

     .FormatConditions(2).Font.ColorIndex = 4

End With

 

Finally, if there is an X in column C, I want to use strikethrough to cross out the words.

 

'if x, then cross-out

   With ActiveSheet.Range("D11:AP" & LastRow)

     .FormatConditions.Add Type:=xlExpression, Formula1:="=$C11=""x"""

     .FormatConditions(3).Font.Strikethrough = True

End With

 Here's what the conditional formatting rules look like after running the macro:

And that’s how you add conditional formatting with a macro. Let me know in the comments below if you have any questions.

Monday, March 15, 2021

Excel Tips from the Best 2021 March Madness Brackets

After a year hiatus it’s finally here, the college basketball March Madness brackets are back! Last year, I made a NFL Draft Game spreadsheet for the first time to try to compensate for the loss of the basketball brackets but it just wasn’t the same (but I did still update it for 2021). This year, the 2021 NCAA men's basketball tournament will be unlike any March Madness that has come before. All games will be played in Indiana, with most in Indianapolis. The schedule has also been change. The First Four would typically be played on Tuesday and Wednesday night with the first round being played on Thursday and Friday. 

Here's the 2021 March Madness schedule:

  • First Four — 4 p.m. start on Thursday, March 18
  • First round — 12 p.m. start on Friday, March 19, and Saturday, March 20
  • Second round — 12 p.m. start on Sunday, March 21, and Monday, March 22
  • Sweet 16 — 2 p.m. start on Saturday, March 27, and 1 p.m. start on Sunday, March 28
  • Elite Eight — 7 p.m. start on Monday, March 29, and 6 p.m. start on Tuesday, March 30
  • Final Four — 5 p.m. start on Saturday, April 3
  • NCAA championship game — 9 p.m. Monday, April 5

Once again, I will be using the best March Madness brackets in Excel, created by David Tyler (and I will continue to use his until he decides to no longer update them). They’re very polished and easy to use. There are only 68 teams in the field but the spreadsheet is already setup to handle up to 128 teams, if they expand in the future. There are two sheets: the bracket and the pool manager. Instructions are included but its very intuitive. 

march madness 2021 bracket spreadsheet template


The First 5 Things I Do When Examining Someone Else's Spreadsheet

As I’ve said countless times before, you can learn a lot by looking at templates made by others. Here are 5 things I do when examining a new spreadsheet:

1. Unhide hidden sheets, columns, and rows: When you make a template others are going to be using, you want to make it look nice and clean and hide anything that could cause confusion to a first time user, which leads to hiding rows, columns, or even entire sheets in a workbook. So, the first thing I do when examining someone else’s template is look for the hidden data. Right click on the sheets tab and click “unhide”. I unhide all the hidden sheets if there are any to see what data is present. Look for any hidden columns or rows as well by seeing if any letters or numbers are skipped.



2. Understand the NamedRanges: Go To Formulas > Name Manager and examine what the named ranges are, what sheets and cells they refer to. Hopefully they're all named well, like in David's brackets.



3. Look at conditional formatting rules: On the Home tab, go to Conditional Formatting, click Manage Rules, then Show formatting rules for This Worksheet to view them all.



4. Look through the formulas: On the Formulas tab, click “show Formulas” to show if they were manually typed in or if there is a formula calculating the values



5. Look through the macros: Hopefully, the person writing the code left lots of good comments so it’s easier to follow along with what each piece of code does



Watch me quickly walk through David's 2021 March Madness brackets going through the five points listed above:


Tuesday, August 11, 2020

Facebook Marketplace Sales Tracking Spreadsheet Template

Like probably most Americans have in 2020, I’ve been trying to stay safe and stay home as much as possible. Instead of going on a summer vacation, we’ve been spending our time and money on decluttering and improving our house. Since we’ve been working from home much more often and soon our kids will begin remote schooling, we decided to turn our guest bedroom into an office/school room. But we’ve been using that spare room as storage space, so first we needed to get rid of all the crap that’s in there. Seriously, you couldn’t even walk around there were so many boxes of stuff we had accumulated over the past eight years.

I decided to start selling the stuff we no longer needed on Facebook Marketplace. After my first few sales, I thought I should really be tracking all this in order to learn from it and improve my sales. So naturally I made an Excel spreadsheet! I’ve turned my sheet into a blank template for you to use as well if you want to get into selling on Facebook Marketplace and tracking your sales. Many Americans have lost their jobs or have reduced hours/wages. Selling goods on FB marketplace is a simple way to make a little additional income.

As always, even if you have no plan to sell anything on Facebook Marketplace, you can still dissect this Excel template to learn some valuable lessons:

  • How to make drop down lists using name manager and data validation
  • How to filter a data table
  • How to use ROUNDUP, IF, TEXT, COUNTIF, MAX, MIN, and AVERAGE functions
  • How to count the number of days between two dates in Excel

Facebook Marketplace Sales Tracking Demonstration

In my spreadsheet, I track several key stats, such as what day of the week you make the most sales. Here's a video tour where I walk you quickly through the spreadsheet. One thing I forgot to finish was to show how the filter works, so if you have any questions about that feel free to let me know.

Selling Price Calculator

One of the most useful features might be the Selling Price Calculator. 90% of people are going to offer you an amount lower than what you’re listing your item for, especially the more expensive it is. I’ve added a feature to the spreadsheet that will calculate how much money you should list your item for sale based on what you want to get plus a markup value based on your historical selling data. As you sell more items on Facebook Marketplace, you’ll see how much of a discount you’re settling for. Once you know that value you know how much to add to the cost of an item. I use the ROUNDUP function to round up to the nearest dollar ($25.50 becomes $26.00).

I haven't sold on other sites such as Ebay or Craigslist but you could probably use this same sheet for those too.

FB MP Sales Tracking Template.xls download

 
Tips for Selling on Facebook Marketplace

Inside the spreadsheet I give a few tips but I've shared some here too:

Tip #1: Check the marketplace for other similar items to get a feel for who is selling what and for how much. Is your item unique or popular?

Tip #2: Set your initial price higher than what you want. 90% of my sales we settled for on average 13% lower than my original asking price. Some of this was me asking too much.

Be fair. When you get greedy is when you don’t make any sales

Tip #3: As far as safety, just be smart about it. If you’re going to meet someone to exchange items, maybe setup your meeting in the parking lot of your local police station. Most people may have their FV profile hidden from you, but you should still be able to see when they joined and how many friends they have. If they joined less than a year ago and/or have less than 30 friends be wary, this could be a fake account.

Tip #4: Bigger/unique items do seem to do better. Probably not going to make a lot if selling old video games (unless they’re really old or rare).

Tip #5: Communication is key. Make the sale. The most annoying part about selling online is communication issues - people backing out of sales at the last minute, leading you on, not fully reading your listing details, etc.

Tuesday, July 7, 2020

Rename Excel Workbook Based on Number of Files Macro


Let’s say you have a task where you want to include a control number in an Excel sheet and in the name of the file which is based on the total number of Excel files contained within a folder. If you’re not familiar with writing VBA macros for Excel, see my getting started guide here.

For this example, there are currently three Excel files saved in a folder with these names:

Doc-Control-01
Doc-Control-02
Doc-Control-03

We want to save our latest document using the name Doc-Control-04, but how does Excel know to use “04” at the end?

As with any complicated task, the first thing I do is break it down into smaller, more manageable steps.

  1. The user selects the folder where to save the Excel documents
  2. The macro saves the open workbook into the folder with a “ZZZ” placeholder in the filename
  3. The macro counts the number of Excel files in the folder.
  4. The macro adds the control number based on this count into the spreadsheet
  5. The macro saves a copy of the workbook in the same folder but replaces the placeholder  “ZZZ” in the file name with the control number count
  6. The macro deletes the first copy the Excel document

Here’s a rundown of the VBA code:

Sub Generate_Documents()

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual
 
Dim Wb2 As Workbook
Set Wb2 = ThisWorkbook
ThisWorkbook.Sheets(1).Select
Wb2.Activate

'---The control number will be in cell G7. For now we input placeholder “ZZZ”
Wb2.ActiveSheet.Range("G7").Value = “ZZZ”

'----save the Excel document VBA----
'dialog box to save the spreadsheet
Dim InitialName As String
Dim fileSaveName As Variant
InitialName = “Control Number: “ & Wb2.ActiveSheet.Range("G7").Value
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, fileFilter:="Excel Files (*.xlsx), *.xlsx")

If fileSaveName = False Then
        MsgBox "File not saved. You must save the file!"
        Exit Sub
       ‘exit the program so we don’t delete the template file
        Else
        Wb2.SaveAs Filename:=fileSaveName
        End If
       
‘now the macro knows what folder to look in to count the files

'Next, create the Control number by counting excel files in the folder and rename
'count existing excel files in the save folder
'First, get the location WB2 was just saved in
Dim WB2Path As String
WB2Path = Wb2.Path

Dim FileCount As Integer
Dim FolderPath2 As String, path2 As String

FolderPath2 = Wb2.Path

path2 = FolderPath2 & "\*.xls*"

    Filename = Dir(path2)
FileCount = 0
    Do While Filename <> ""
       FileCount = FileCount + 1
        Filename = Dir()
    Loop
    'MsgBox FileCount
   
     
    '---control number. If less than 10 add a 0 to display 01, 02, etc.
If FileCount < 10 Then
Wb2.ActiveSheet.Range("G7").Value = "0" & FileCount
Else
Wb2.ActiveSheet.Range("G7").Value =  FileCount
End If

Dim OldName As String, newName As String
OldName = Wb2.FullName

‘use the replace function to automatically replace placeholder “ZZZ” with the document control number
newName = Replace(OldName, "ZZZ", Right(Wb2.ActiveSheet.Range("G7").Value, 2))

‘save a copy of the sheet with the control number in the file name
Wb2.SaveAs Filename:=newname

‘delete the old workbook
Kill OldName

'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Let me know in the comments below if you have any questions how to rename a workbook based on the number of files in a folder.

Monday, June 22, 2020

Excel Macro to scroll to the top or bottom of the sheet


If you have a long sheet and are constantly scrolling all the way down to the bottom then back up to the top, here are two quick macros you can use to instantly go to the top or the bottom of the active sheet.

Sub GoTo_Top()
    With ActiveSheet
        Application.Goto Cells(1, 1), True
        End With
       
End Sub

Sub GoTo_Buttom()
    With ActiveSheet
        LastRow = Cells(Rows.Count, 2).End(xlUp).Row
        Application.Goto Range("B" & LastRow), True
    End With
End Sub

Use the developer tab to insert a command button, then link it to your macro to make it super easy for even the most inexperienced Excel user to instantly move from the top and the button of the spreadsheet.

If you don’t see the Developer tab at the top, go to File -> Options - > Customize Ribbon

I hope you enjoyed this quick tip! Sign up for my email list for more Excel tips.

Tuesday, May 12, 2020

Unique Excel Uses: Drum Machine

As someone who was a drummer in high school and college, this might be my favorite unique use of Excel yet. Dylan Tallchief has made an actual drum machine in an Excel spreadsheet. How cool is this?!
drum machine excel spreadsheet


Who knew we'd be able to make music in Excel? It really is a miracle program. Watch the video below to see the drum machine in action.


The part of the video where Dylan gets into the description of getting the VBA code to work is especially interesting to me.

sleepTime = 60 / Range("C23").Value * 1000 / 4   '2 will need to change to 4 when i add more resolution
swingL = sleepTime + ((sleepTime / 5) * Range("C26"))
swingS = sleepTime - ((sleepTime / 5) * Range("C26"))

Below is a video of myself messing around with the sheet and showing you how to change the beats per minute (BPM aka tempo) or how to add a swing groove to the sequence.


This is one template you'll definitely want to try and play around with yourself. Download the drum machine spreadsheet for yourself using the link in Dylan's video.

I'll have to add drum machine to my list of unique uses for Microsoft Excel spreadsheets. If you have your own unique use of Excel please do let me know!

Monday, October 14, 2019

How to remove ordinal abbreviations from dates and numbers

Did you know there is a term for the two letters that follow the number of a date? You know, the "st" in 1st; the "nd" in 2nd; the "rd" in 3rd; the "th" in 4th? They're called ordinal abbreviations. These ordinal abbreviations are actually hybrid contractions of a numeral and a word. 1st is "1" + "st" from "first". Similarly, "nd" is used for "second" and "rd" for "third". Sometimes they're also referred to as elevated terminals due to the way they're typically written: 1st, 2nd, 3rd, 4th, etc..

What does this have to do with Excel?

Recently, a reader asked me a question. He was the the date in column B written as 11th, 1st, 2nd, etc., the month written out in column C, and the year in column D. So the question was how to transform these three separate columns: 11th December 219 into this one single column in Excel: 11/12/2019.



Here's how to solve this seemingly complex problem: break down into smaller problems.

First, to combine multiple columns into one, use concatenate. =b2&"/"&c2&"/"&d2.

Next, to change a month written out to a number, use this formula: =MONTH(1&C2)

Third, use SUBSTITUTE to find the ordinal abbreviations and replace them with nothing.
=--SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B3,"st",""),"nd",""),"rd",""),"th","")

Finally, put all the elements together for one long formula that seems complicated but is quite simple when you break it down into parts:

=--SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B2,"st",""),"nd",""),"rd",""),"th","")&"/"&MONTH(1&C2)&"/"&D2

Monday, March 25, 2019

How to hide checkboxes and rows in Excel with VBA

I recently received a question about how to hide or collapse a row if a checkbox in that row wasn’t checked. There are a lot of good lessons in this example. When you’re stuck on a problem, the best thing to do is to break it down into smaller problems and solve each one at a time. Let's do it!


How to Insert Checkboxes in Excel


The first lesson is how to add a checkbox to an Excel sheet. Go to Developer tab then Insert. There are two types of checkboxes: Form Control and ActiveX Control. For this example, we are going to use Form Control checkboxes because you can link these directly to a cell.




How to link a checkbox to a cell


The next lesson is how to assign a checkbox to a cell. We’re going to do this to help with hiding the rows later. When you create the first Form Control checkbox in cell A2, in the formula bar type “=$B$2” to assign B2 to the checkbox. Now, if the checkbox is checked B2 should read TRUE, if not selected it should say FALSE.

**The one downside to this method is if you need 100 checkboxes it could take some time to manually assign each checkbox to a cell. There is probably a way to automate this task, however, for simplicity of this example we’re going to say we only need five checkboxes and assign them all manually.**

Now your example sheet should look like this:



How to hide rows based on a cell’s value in VBA

The hiding of all the checkboxes and rows will be done automatically with a VBA macro. If you’re new to macros see this gettingstarted guide. 

Again, break it down into smaller problems. First, let’s figure out how to hide rows based on a condition, the TRUE or FALSE value in our helper column.

Define the first row that contains data we might want to hide:
BeginRow = 2

Define the last row that might contain data we want to hide.
EndRow = 5

Define the column number of our helper info, the column with the true or false values.
ChkCol = 2

Loop through the range of rows we just defined and if the value of the cell in our helper column is false, then hide that entire row:

    For RowCnt = BeginRow To EndRow
        If Cells(RowCnt, ChkCol).Value = False Then
            Cells(RowCnt, ChkCol).EntireRow.Hidden = True
        End If
    Next RowCnt

How to hide checkboxes automatically with macro

Dim CB As Shape
Dim sh As Worksheet

Set sh = ActiveSheet

We need to loop through all the shapes in the active sheet, see if they are the form control type of Check Box:

For Each CB In sh.Shapes
  If CB.Type = msoFormControl Then
    If CB.FormControlType = xlCheckBox Then
      'MsgBox CB.Name, vbOKOnly
     
      'if check box is checked, keep it visible, otherwise, hide it
      If CB.OLEFormat.Object.Value = 1 Then
        CB.OLEFormat.Object.Visible = True
        Else
        CB.OLEFormat.Object.Visible = False
End If
     
    End If
  End If
Next CB

Full Macro to Hide Rows and Checkboxes

Here’s the final code that hides entire rows based on checkbox is checked or not.

Sub Hide_checkboxes()

Dim CB As Shape
Dim sh As Worksheet

Set sh = ActiveSheet
For Each CB In sh.Shapes
  If CB.Type = msoFormControl Then
    If CB.FormControlType = xlCheckBox Then
      'MsgBox CB.Name, vbOKOnly
     
      'if check box is checked, keep it visible, otherwise, hide it
      If CB.OLEFormat.Object.Value = 1 Then
        CB.OLEFormat.Object.Visible = True
        Else
        CB.OLEFormat.Object.Visible = False
End If
     
    End If
  End If
Next CB

'now hide the rows
    BeginRow = 2
    EndRow = 5
    ChkCol = 2

    For RowCnt = BeginRow To EndRow
        If Cells(RowCnt, ChkCol).Value = False Then
            Cells(RowCnt, ChkCol).EntireRow.Hidden = True
        End If
    Next RowCnt


End Sub

How to unhide rows and checkboxes in Excel

Conversely, I also made a code to reset everything and unhide all checkboxes and unhide all rows:

Sub Unhide_checkboxes()

Dim CB As Shape
Dim sh As Worksheet

Set sh = ActiveSheet
For Each CB In sh.Shapes
  If CB.Type = msoFormControl Then
    If CB.FormControlType = xlCheckBox Then
      'MsgBox CB.Name, vbOKOnly
     
      'if check box is checked, keep it visible, otherwise, hide it
      If CB.OLEFormat.Object.Value = 1 Then
        CB.OLEFormat.Object.Visible = True
        Else
        CB.OLEFormat.Object.Visible = True
End If
     
    End If
  End If
Next CB

'now hide the rows
    BeginRow = 1
    EndRow = 5
    ChkCol = 2

    For RowCnt = BeginRow To EndRow
        If Cells(RowCnt, ChkCol).Value = False Then
            Cells(RowCnt, ChkCol).EntireRow.Hidden = False
        End If
    Next RowCnt
   
End Sub

How to insert a button and link to a macro

Finally, for ease of use we can add two buttons to our sheet to run each one of the macros. Go to Developer tab, insert command button.



Watch the video below to see how the macro to hide checkboxes and rows works.



As you can see, there is much to glean just from this one example.