This compact text is a powerful introduction to the ExcelVBA computing environment. The book presents some of the most useful features of Excel. First by introducing mathematical puzzles that will grab the reader’s attention with the reader invited to think hard on solving those puzzles. Then, solutions are presented in a logical manner. The book goes on to describe modern and uptodate engineering problems and their solutions. Based on many years of the authors’ teaching, the book provides a practical, useful and enjoyable learning methods for readers to become expert in Excel and its application to engineering.
Conclusion
Chapter highlights practical Excel and VBA fundamentals, including how to work with one- and two-dimensional tables, write code to compute class averages, perform string operations useful for tasks such as basic computer game development, and apply matrix operations to solve numerical puzzles often seen in newspapers It also demonstrates the limitations of built-in Excel functions and shows how VBA’s programming logic offers greater flexibility and power for more complex solutions.
E1:1 Which word has three consecutive pairs of letters? Find out via manipu- lation of the VBA code that was provided in this chapter.
Bookkeeper is the word with three pairs of consecutive letters, a handy linguistic aside This article also explains how to write an MS Excel VBA macro to determine the last Saturday in October for any given year, with concrete results for 2028 and 2100 The last Saturday in October is significant in the United Kingdom because it marks the switch back to Greenwich Mean Time To implement the solution, the day-of-week calculation is modified to run iteratively and search for Saturday, ensuring the macro correctly identifies the final October Saturday for any year.
On the Ex01-06.xlsm workbook, the Main worksheet holds three given letters in cells B1:D1 The current VBA routine already splits every three-letter word and writes its letters to columns Y, Z, and AA The enhancement filters the results so that only letters that match the corresponding B1:D1 entries are recorded in Y, Z, and AA: for each word, the first letter is written to Y only if it equals B1, the second to Z only if it equals C1, and the third to AA only if it equals D1.
Note that this problem shall be explored in further detail in Chap.2.
In this chapter, we shall explore the fun way in which Mr games to the next level and learn algorithm building in the process.
Example 2.1 The Scrabble word game
Scrabble is a word game for two to four players who score points by placing letter tiles on a 15-by-15 board Each tile bears a single letter, and players form words in a crossword fashion that read left to right across rows or downward in columns, with every word required to be found in a standard dictionary such as the Oxford English Dictionary.
Dictionary, also known as OED.
The game is available for sale in very many countries and there are several hundred million players and thousands of Scrabble clubs around the world.
In this word game, players form words on a board, and the total word score is the sum of the points assigned to the individual tiles that compose the word Each tile carries a unique score, so the value of a word depends on the specific tiles it uses For example, if the word SPIRE is formed, its score equals 1 + 3 + 1 + 1 + 1 = 7.
Using the tiles shown in Fig.2.1write a VBA code that may form as many words as possible.
Refer to Fig.2.1which shows the tiles picked by the four Scrabble players: a (top-left),b (top-right),c(bottom-left), and d(bottom-right).
This article explains how to write VBA code that accomplishes a specified set of tasks, assuming readers already have a basic working knowledge of VBA It also acknowledges the growing trend of teaching coding to children at earlier stages of schooling, reflecting broader educational shifts By focusing on practical VBA solutions that align with this knowledge baseline, the guide aims to help developers implement effective automation with confidence.
T Muneer and S Ivanova, Excel-VBA, https://doi.org/10.1007/978-3-030-94085-0_2
• Read the letters for any given player
• Sequentially read all the Z-lettered words in a given dictionary, where Z takes the value of 2, 3, 4, 5, 6 and 7.
• Sequentially match the words from letters provided
The code is displayed in Table2.1with line numbers identifying each line of the code and blocks of program separated out Explanation of the code is provided here.
The main program flow is defined in lines 1–10, with the word-forming sub-routine invoked at line 6 The loop in lines 4–7 directs the machine to generate word phrases of increasing length, producing sequences of 2, 3, 4, 5, 6, and 7 words in order The dedicated word-forming sub-routine starts at line 11, marking the beginning of the specialized processing module.
This exercise was handed to a diverse group of participants, spanning ages and professional backgrounds—from a first-year high school student to a retired business executive and an English language teacher Table 2.2 lists the scores achieved by these volunteers, reflecting their varied performance These volunteer scores are then compared with the current software’s performance to evaluate how the software stacks up against human benchmarks.
At this stage, the reader is encouraged to execute the code shown in Table2.1and get a list of the words formed by the software.
Note that in the Exercises section we revisit the application of Example 2.1 to demonstrate more rigorous word-formation techniques In the same vein, Figures 2.2 and 2.3 respectively show letter tiles for four players and a blank tile that may be used as a wild card.
Fig 2.1 The Scrabble board and alphabet tiles picked by one player
Table 2.1 VBA code for Example 2.1: Scrabble word game
2 Dim strlnt, iwrdlnt As Integer
12 Dim amfc(22), bmfc(22), singlet(26) As String
13 Dim aword, bword, cword, dword, eword(10000), frstchr As String
14 Dim sglet, sdlet, declet(26), vallet(26) As Integer
15 Dim givenlet(26), foundlet(26) As Integer
17 NgivenLet = Sheets("Main").Cells(4, 2).Value
27 declet(km) = Sheets("Dictionary").Cells(km, 2).Value
33 singlet(km) = Sheets("Main").Cells(1, km + 1).Value
39 If (uplet = declet(kn)) Then
40 Sheets("dump").Cells(2, kl).Value = vallet(kn)
44 If (uplet = singlet(km)) Then
48 Sheets("dump").Cells(2, kl + 26).Value = sumuplet
2 Games and Puzzles 17 sanet.st
52 bword = Sheets("Dictionary").Cells(i, 1).Value
65 If (bmfc(M) singlet(km)) Then
73 Sheets("dump").Cells(j + 4, 24).Value = cword
79 If (uplet = declet(kn)) Then
80 Sheets("dump").Cells(j + 4, kl).Value = vallet(kn)
84 If (uplet = bmfc(km)) Then
88 Sheets("dump").Cells(j + 4, kl + 26).Value = sumuplet
100 wallet = Sheets("dump").Cells(2, km + 1).Value
101 givenlet(wallet) = Sheets("dump").Cells(2, km + 26).Value
106 wallet = Sheets("dump").Cells(kn + 4, km + 1).Value
107 foundlet(wallet) = Sheets("dump").Cells(kn + 4, km + 26).Value
111 sglet = Sheets("dump").Cells(2, nk).Value
112 fglet(sglet) = Sheets("dump").Cells(2, 26 + nk).Value
116 sdlet = Sheets("dump").Cells(kn + 4, km).Value
117 fdlet(sdlet) = Sheets("dump").Cells(kn + 4, km + 26).Value
118 If (fdlet(sdlet) > fglet(sdlet)) Then
119 Sheets("dump").Cells(4 + kn, 23).Value = "X"
124 codeX = Sheets("dump").Cells(kn + 4, 23).Value
125 cword = Sheets("dump").Cells(kn + 4, 24).Value
127 Sheets("Main").Cells(jfinal, 24).Value = cword
Note that the fi le Ex02-01.xlsm contains the above VBA code
2 Games and Puzzles 19 sanet.st
Fig 2.2 Alphabet tiles picked by four Scrabble players
Table 2.2 Word-forming scores achieved by Scrabble players
Player Number of words formed
Figure 2.3 depicts a Scrabble board with the alphabet tiles selected by one player The second tile from the left is a blank tile, acting as a wildcard that can substitute for any letter This wildcard expands possible word forms and can boost the overall word-forming score, illustrating how a single wildcard increases scoring potential.
Newspapers around the world carry games and puzzles on their back pages. One such game is called ‘word-wheel’ A typical example of such word-wheel is shown in Fig.2.4.
Players are invited to a word game where they form words of at least three letters from the letters shown in the figure Each word must include the central letter A, and no letter can be reused within a word Additionally, there is exactly one nine-letter word that uses all the letters displayed in the figure.
Let us start nice and simple We can easily form words such as‘tan’and
‘taunt’ Using your memory, try to make as many words as possible and keep a paper record of that Now let us see how we can use Excel–VBA.
Open the file Ex02-02.xlsm and launch the VBA code by pressing Alt+F11 to study the module Compare this code with Example 2.1 found in Ex02-01.xlsm; the VBA in both files is highly similar, with the key difference that the current version relies on the central character 'A' In the Ex02-02.xlsm code, search for the string 'esschar' that stores the central character in memory, and you’ll notice it is used in only two locations, showing how the previous code can be reused and adapted to solve the 'word-wheel' example.
For context, refer to the Discussion of Example 2.1 In this iteration, the exercise was again assigned to the same group of players, and Table 2.3 lists the scores achieved by the volunteers These scores are then compared once more with the performance of the current software.
Users are encouraged to run the code shown in Table 2.1 to generate the complete list of words produced by the software for the word wheel shown in Fig.2.4.
Table 2.3 Word-forming scores achieved for word-wheel puzzle
Player Number of words formed
2 Games and Puzzles 21 sanet.st
Given two large integer numbers, each of which contains a large number of digits, write a program to compute the exact product of the two numbers.
The problem may be analyzed by placing ourselves in the place of computer.
As an example, let us consider the multiplication of the following two numbers fromfirst principles,
The above procedure may be used to multiply numbers of any magnitude by the following steps:
1 Read and save in a dimensional space the two numbers, the multiplicand and the multiplier.
2 Select thefirst digit of the multiplier.
Multiply the above single-digit number by each digit of the multiplicand, starting from the extreme right-hand digit and moving left Take care of carryover at every step, ensuring that any overflow from a product is carried to the next place value Store all the resulting product digits in a two-dimensional array to keep the partial results organized for subsequent summation.
4 Keep repeating step 3 until all digits of multiplicand have exhausted. Fig 2.4 A word-wheel
5 Add the digits in the two-dimensional array taking care of the shift to the left required between two consecutive rows, as shown in above demonstration.
As a trial let us attempt the following problem in which a seven digit number is multiplied with another seven digit number:
Launch thefile Ex02-03.xlsm and view the VBA code contained within it. Key in the multiplicand and the multiplier as shown in the worksheet named
Conclusion
This chapter deepens the use of Excel and VBA for word-forming and number crunching, enabling exact products of very large numbers, factorials of large values, and raising integers to large powers It presents examples rooted in historical narration and introduces more advanced matrix operations designed to solve complex numerical puzzles.
A heterogram is a word composed of non-repeating letters, with each alphabet used only once Examples of five-, seven-, and ten-letter heterograms include brick, stumped, and blacksmith Using the techniques from Sections 2.1 and 2.2, list all ten-letter heterograms found in the dictionaries provided with Ex02-01.xlsm and Ex02-02.xlsm, by writing a VBA code to perform this task Following E2.1, E2.2 requires collecting in a text file all words that end with the letters 'ion'.
Refer to Example 2.1 and Figure 2.1 for the setup The digital file Ex02-01.xlsm provides a VBA script to illustrate the approach Extend this VBA code to compute and return the score for each word formed in the latter example, delivering clear per-word scores as the output.
Refer to Example 2.1 and Figure 2.2 A VBA routine is provided in the digital file Ex02-01.xlsm Extend that code to compute the score for each word that can be formed by the four players—A, B, C, and D—and to determine the total score for every formed word The objective is to obtain both the per-word scores and the overall totals, enabling analysis of which words yield the highest scores.
find which player has the potential to get the highest score.
Refer to Example 2.1 and Fig 2.3 A VBA macro is provided in the digital file Ex02-01.xlsm Extend this code to compute the score for every word that can be formed using the blank tile, which acts as a wildcard and can stand in for any letter, thereby increasing the potential word-forming score Table 2.7 lists the points assigned to each Scrabble letter.
Copyrights on a large number of books have expired, and many titles are now freely accessible online through a variety of websites A landmark example is The Arabian Nights Entertainments, which is available from Project Gutenberg, a pioneering digital library that hosts public-domain works for free online access.
2 Games and Puzzles 31 sanet.st
Complete’ That eBook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever You may copy it, give it away, or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.net The book posted on January 24,
2009 [EBook #5668] has the character set encoding: ISO-8859-1.
Download one such book and then write a VBA code that will enable you to predict words that follow commonly used words That code may read two consecutive words, one at a time, search for one of your chosen common word and then provide the predicted word that follows your chosen word. E2:7 Create a textfile that contains a large number (say, 20) of 50 digit numbers. Write a VBA code to obtain the sum of those numbers You may use lessons learnt from Example2.3.
Problem E2:8 presents a four-player Bridge deal and asks for the probability that each player ends up with exactly one suit (one player with all spades, one with all diamonds, and so on), with the exact value computed from Ex02-03.xlsm using the method shown in Example 2.3 Problem E2:9 follows Example 2.6 and introduces the Wijuko/Sujiko puzzle; in Fig 2.9, six numbers are missing and must be filled in with single-digit integers so that the sums around the circles equal the numbers inside those circles, and after solving the puzzle the nine squares will contain the digits 1 through 9. -**Support Pollinations.AI:**🌸 **Ad** 🌸 Ace your Bridge probability and puzzle-solving articles with AI-powered writing—[Support our mission](https://pollinations.ai/redirect/kofi) to keep AI tools free for creators!
T Muneer, J Usher, Teaching computer programming skills: a stimulating approach J Scottish Math Council 45 – 52 (1991)
Table 2.7 Points worth of each letter in Scrabble word game
Error Analysis Using Chauvenet ’ s Technique
Researchers continually perform experiments that involve data collection, whether manually or with data-loggers, and despite careful work, errors can creep into every dataset To remove flawed points consistently rather than by whim, Chauvenet’s criterion provides a principled way to identify and reject outliers The method defines a probability band centered on the mean of a normal distribution that should reasonably contain all n observations, and any values outside this band are treated as outliers to be removed After exclusion, the mean and standard deviation are recalculated using the remaining data and the new sample size, ensuring a clean dataset for subsequent analysis Practically, this involves computing the number of standard deviations corresponding to the band bounds (dmax) and comparing the absolute deviation |xi − mean|/s to dmax for each datum.
• Obtain arithmetic mean, Xm & Standard deviation, SD of the data‘X’where the sample size of X is‘n’data points.
• Obtain deviation for each data point, di = Xi– Xm.
Using Chauvenet’s criterion, examine the dataset for inconsistencies and potential outliers The criterion states that a data point should be considered suspect if the probability of obtaining a deviation as extreme as the observed one, under the assumed population distribution, is less than 1/(2N), where N is the sample size Practically, compute each datum’s standardized deviation and its tail probability (often via the normal distribution’s complementary error function) and flag those observations whose probability falls below the 1/(2N) threshold, as these may not belong to the same population.
T Muneer and S Ivanova, Excel-VBA, https://doi.org/10.1007/978-3-030-94085-0_3
These steps are demonstrated via Example3.1.
Example 3.1 Quality control of data using Chauvenet ’ s criterion
Ten length measurements of the object were recorded and shown in the second column from the left in Table 3.1 Chauvenet’s criterion was then applied to these data to perform quality control, identifying potential outliers and enhancing the reliability of the measurements.
To start, compute the data mean Xm = 5.613 and the standard deviation SD = 0.5944, and use these to populate the third and fourth columns of Table 3.2 In this example, SD is 0.5944 Next, calculate the di/SD ratio for each observation and place these ratios in the corresponding cells of Table 3.2 The calculations for the fifth and sixth columns then proceed from these ratios.
Table 3.1 Length of a given object as recorded by 10 volunteers
Reading no Length of the object, X
Table 3.2 Analysis of the data presented in Table 3.1 regarding any suspect readings
Length of the object, X di abs(di)/
In the numerical analysis workflow, across the columns, the parameter n * erfc(abs(di)/SD) is calculated and Chauvenet’s test is applied The erfc function is the complementary error function and is available as a built-in function in Microsoft Excel; in Excel/VBA it can be accessed with Application.erfc(z), where z is the input argument This approach combines erfc calculations with Chauvenet’s criterion to identify outliers using standard spreadsheet tools.
Analysis shows that the third and fifth readings are suspect, so the recommended action is to reject these readings; the file Ex03-01.xls provides all the steps described above.
Example 3.2 Solution of a fourth order algebra equation
Gerolamo Cardano, a sixteenth‑century mathematician, published the landmark work Ars Magna in 1545, a breakthrough that laid the groundwork for analytic methods in algebra He is regarded as the originator of techniques for solving cubic and quartic equations, establishing his lasting influence on the development of mathematical problem‑solving (Branson 2013).
A quartic algebraic equation is the highest order equation that may have an analytical solution, there being no generalized solution for quintic equation, i.e an equation offive unknowns.
In 1897, Cambridge University scholars H S Hall and S R Knight published Higher Algebra (Macmillan, London), reintroducing Cardano’s work and presenting a fourth-order equation (Eq 3.1) along with its solution.
YẳX 4 2X 3 5X 2 ỵ10X3ẳ0 ð3:1ị The roots of this equation are,
Use the Bisection method to obtain the roots of Eq (3.1).
Solving a quartic algebra equation via Bisection method.
The bisection method, also called the interval halving method, is a straightforward root-finding technique that requires two initial approximations It will converge when these initial guesses bracket the root, meaning they lie on opposite sides of the root, allowing the interval to be halved repeatedly until the root is isolated.
3.1 Error Analysis Using Chauvenet ’ s Technique 35 sanet.st
From Fig 3.1, the two initial approximations are X A and X B and their mid-point isX N The function, Y is evaluated at the latter three points and then the following logic is used,
If Yð 1Y3ị[0; then XAẳXn; else XBẳXn:
During each iteration, Y3 is obtained, and the routine halts when Y3 falls below the predefined error tolerance To ensure safe operation, a counter tracks the number of iterations, and the process terminates once a preset limit is exceeded.
Thefile Ex03-02.xlsm provides solution to this problem which is based on a macro The VBA code for this macro is provided in Table3.3.
Tables 3.3 and 3.4 present the VBA code for the Bisection method and the corresponding Excel output, with the code returning the roots of the target equation only within the interval defined by cells B15 and B16 (as shown in Table 3.4); to discover additional roots, simply adjust these limits.
Fig 3.1 Bisection method for root fi nding of an algebraic equation
Table 3.3 VBA code for Bisection method
Sub BisectionMethod() X1 = Sheets("Compute").Cells(15, 2) X2 = Sheets("Compute").Cells(16, 2) niter = 0
' TOLERANCE FOR FUNCTION SET AT 1E-8
If (Abs(YM) < 0.00000001) Then GoTo Line1
If (niter > 1000) Then GoTo Line1
Else niter = niter + 1 Sheets("Compute").Cells(niter, 9) = X1 Sheets("Compute").Cells(niter, 10) = X2 Sheets("Compute").Cells(niter, 11) = YM GoTo Line2
Sheets("Compute").Cells(18, 2) = XM Sheets("Compute").Cells(18, 4) = niter End
3.1 Error Analysis Using Chauvenet ’ s Technique 37 sanet.st
Table 3.4 Output generated in MS Excel
Example 3.3 Solution of a system of algebra equations: Hooke and Jeeves method
Amina and Fariha are Afghan princess sisters, with Amina currently 8 years old and Fariha 16 Fariha is twice Amina’s age, and in 16 years their ages will be in the ratio 4:3 (one-and-a-third), which confirms the ages as 8 and 16. -**Support Pollinations.AI:**🌸 **Ad** 🌸 For more engaging articles and creative content solutions, [support our mission](https://pollinations.ai/redirect/kofi) to keep AI accessible for everyone.
Let us denote the respective ages of Amina and Fariha as X(1) and X(2). Note that the above problem can be translated into two simultaneous equa- tions (Eqs.3.2and3.3),
While the equations can be solved with the matrix techniques described in Chapters 1 and 2, this section introduces a far more powerful method capable of handling both linear and nonlinear systems These procedures belong to a branch of mathematics known as numerical analysis, which focuses on robust algorithms for solving complex problems across science and engineering.
Optimization techniques allow solving systems of simultaneous equations, fitting linear or nonlinear models, and determining the maximum or minimum values of a given function These capabilities underpin a wide range of applications across all branches of engineering, driving advances in design, analysis, and performance improvement.
Equations 3.2 and 3.3 may easily be converted into an optimization problem as shown in Eq (3.4),
ZẳẵX 2ð ị2X 1ð ị 2 ỵẵfX 2ð ị ỵ16gf1:3333 X 1ð ð ị ỵ16ịg 2 ð3:4ị Or,
Note that once X(1) and X(2) have converged, Z will assume nil value.
We shall try to find those values of X(1) and X(2) that return a minimum value of Z.
Various optimization techniques can readily handle this task, and we will illustrate a direct search approach called Pattern Search, devised by R Hooke and T A Jeeves (Direct search solution of numerical and statistical problems, Journal of the ACM, 8, 1961).
Conclusion
This chapter offers practical examples of data quality control using proven statistical procedures and demonstrates optimization techniques for solving linear and nonlinear algebraic equations, providing ready-to-apply insights that enhance engineering design and practice.
E3:1 Chauvenet’s criterion was introduced via Example 3.1 Develop an Excel/VBA code to enable construction of Table3.2.
E3:2 Colebrook’s model for obtaining the friction factor related to fluid flow in pipes and ducts is given by Eq.3.4.4,
Use the Bisection method for solving this nonlinear equation for the data given in Example3.4.
Aishah, a Canton-based chemist, is focused on determining the minimum solubility (S) of a compound she has synthesized in her laboratory, and the article examines how solubility varies with temperature (t) by presenting the relationship that governs S as a function of temperature, offering insights into solubility behavior for practical applications and formulation optimization.
Fig 3.3 The Goal Seek dialog box
Solving this minimization problem can be efficiently approached by converting it into a root-finding task: differentiate the objective function to obtain the derivative and then locate its root Apply the bisection method to approximate this root within the interval 3 < t < 9, which yields the stationary point corresponding to the optimum of the original function.
Refer to Example3.2for algorithmic details of the bisection method. Answer: t = 7.81, S =−703.73
E3:4 Refer to Example 3.4 wherein the Newton’s method of root finding was presented Redo Exercise 3.3 by replacing bisection method with Newton’s method.
E3:5 Rafay of Leithville is a process engineer whose laboratory tests have pro- vided the following data that relate the saturation pressure, p sat and saturation temperature T:
Rafay aims to model the saturation pressure with the relation p_sat = exp(A − B/(T + C)) Using the MS Excel Solver, he seeks the optimum values for A, B, and C that best fit the data The problem can be converted to a function minimization task by building a table that computes the residuals between observed p_sat values and those predicted by the model, then minimizing the sum of squared residuals to obtain the best parameters In this way, Solver provides the optimal A, B, and C to describe the relationship.
To build the p model, generate the third column by applying trial values of A, B, and C The fourth column, titled Residual, is computed as the absolute difference between p sat and p model (Residual = Abs(p sat − p model)) The sum of these Residual values produces the total residual, which serves as the Objective Function to be minimized using MS Excel Solver This approach tunes A, B, and C to align the model predictions with measured p sat values, improving model accuracy.
E3:6 MoGulam is an industrial engineer who has obtained the following rela- tionship for inventory cost of engine components:
At any given time, a minimum of 3000 components must be held in stock. Find that value of x that minimizes C(x).
This exercise presents a constrained optimization problem where x must be greater than 1000 It can be solved with Microsoft Excel Solver In Solver, open the 'Subject to Constraints' section and insert the constraint by clicking the Add button to ensure the lower bound x > 1000 is enforced during optimization.
W.B Branson,Solving the Cubic with Cardano Convergence (September 2013) http://www.maa. org/press/periodicals/convergence/solving-the-cubic-with-cardano.
C.F Colebrook's Turbulent Flows in Pipes, with particular reference to the transition region between the smooth and rough pipe laws (1938–39) examines how roughness influences turbulence and delineates the transition between smooth- and rough-pipe friction behavior L.F Moody's Friction Factors for Pipe Flow (1944) provides essential empirical correlations for predicting friction factors in pipe systems across different Reynolds numbers and roughness, serving as a practical design reference Taken together, these works underpin the core understanding of turbulent pipe flow friction and the transition between smooth and rough regimes, informing both theoretical analysis and engineering practice.
P.K Swamee, A.K Jain, Explicit equation for pipe- fl ow problems Proc, of the ASCE J of the Hydraulics Division 102(HY5), 657 – 665 (1976)
Computer Graphics with MS Excel and VBA
MS Office products offer many options for manually or programmatically gener- ating graphics Unfortunately, they are not popular enough Most people perceive
MS Excel as a spreadsheet and calculation program, and the maximum they can imagine as possibilities is to plot a chart on that data.
Microsoft Excel now enables you to work with both raster images and vector shapes, unlocking a wide range of graphic capabilities within spreadsheets You can create and manipulate line segments, arrows, rectangles, triangles, polygons, polylines, and other vector objects, expanding your design and visualization options This expanded toolkit, especially when paired with VBA, opens up powerful possibilities for automating graphics, enhancing charts, and building dynamic, interactive reports.
The following examples show ‘tricky’ approaches with which MS Excel can perform some unexpected graphical tasks These approaches can be classified as follows:
• Pseudo-raster graphics—by colored cells (type 1);
• Pseudo-raster graphics—through Shapes collection (type 2);
• Combination of raster (bitmap) and vector graphics;
Example 4.1.1 RGB definition and use of gray shades
MS Excel can render data in grayscale or color using the RGB color model The RGB() function takes three arguments—red, green, and blue—each ranging from 0 to 255 When all three components share the same value, the result is a shade of gray; the smaller that common value, the darker the gray, while values closer to 255 yield lighter tones This approach lets you set precise grayscale tones or vibrant colors by tweaking the red, green, and blue components, enabling consistent formatting across cells and charts. -**Support Pollinations.AI:**🌸 **Ad** 🌸Get smart with MS Excel color magic—[Support our mission](https://pollinations.ai/redirect/kofi) to keep AI tools free for content creators like you.
T Muneer and S Ivanova, Excel-VBA, https://doi.org/10.1007/978-3-030-94085-0_4
47 sanet.st darker gray and vice versa—if they are closer to 255, the color is getting closer to white.
Develop a function that, given an input value and the left and right bounds of the range in which this value varies, returns a grayscale intensity from 0 to 255 that is used as an argument to theRGB() function When the value equals the minimum bound, the result is black; when it equals the maximum bound, the result is white; and values between bounds yield a medium gray color.
The solution to this problem is demonstrated in the file Ex04-01.xlsm. Module1 includes a function GrayColor() and a executable sub-routine Draw_GrayShades(), see Table4.1.
• The functionGrayColor() returns a value between 0 and 255 The argu- ments areValueand lower limitMinand upper limitMax, which define the range ofValue.
The Draw_GrayShades subroutine can be launched from the list of available macros or with a button, and it uses the Interior.Color property and the RGB() function to set the background color of cells to a gray shade.
After executing the procedure, 16 cells in row 1 of the active sheet are colored with grayscale shades that correspond to the value range from Min = 1 to Max = 16 Using the same value for all three RGB components yields a gray color, with RGB(0,0,0) representing black and RGB(255,255,255) representing white By setting the gray component anywhere between 0 and 255, you obtain the corresponding gray shades, creating a continuous grayscale gradient across the row.
Table 4.1 Function GrayColor() and procedure Draw_GrayShades(), saved in Module1 in Ex04-01.xlsm
Function GrayColor(ByVal Value#, ByVal Min#, ByVal Max#) As Integer 'gray color adjustment function for visualization
GrayColor = (Value - Min) / (Max - Min) * 255
For i = Min To Max gray = GrayColor(i, Min, Max) ActiveSheet.Cells(1, i).Interior.Color = RGB(gray, gray, gray) Next
Example 4.1.2 RGB definition and use of false- and pseudo-colors
Color graphics are generally more engaging than grayscale images, but grayscale data is often colored to improve perceptual clarity When certain values fall outside the human eye’s color-detectable range (roughly 300–700 nm), those values are represented with false colors A grayscale image that encodes variables such as temperatures, albedo, or atmospheric pressure can be converted into a pseudo-color image to reveal patterns, provided we map the data value within the full range to a color spectrum In this mapping, values near the minimum often appear dark blue and values near the maximum appear red or magenta, creating intuitive color scales that enhance data visualization and interpretation.
Create a procedure that, given a numeric value and its range limits (minimum and maximum), maps that value to three RGB components—red, green, and blue—each in the 0–255 interval, representing the three primary colors The resulting R, G, and B values can then be used as arguments to theRGB() function to render the corresponding color.
The solution to this problem is demonstrated in the file Ex04-02.xlsm. Module1 includes a sub-routine FalseColor() and a executable sub-routine Draw_FalseColorShades(), see Table4.2.
FalseColor() is a subroutine that computes the RGB components of the color corresponding to the input variableValue It does this by evaluating how far variableValue differs from the predefined limits Min and Max and adjusting the red, green, and blue channels accordingly to reflect that difference.
Figure 4.1 shows gray shades and color shades for values ranging from Min = 1 to Max = 16, comparing four rendering methods: (a) grayscale without gamma correction, (b) gamma-corrected grayscale colors, (c) false colors without gamma correction, and (d) gamma-corrected false colors The image is generated within Ex04-03.xlsm, illustrating how gamma correction influences perceptual brightness in both grayscale and false-color representations.
4.1 Computer Graphics with MS Excel and VBA 49 sanet.st
Figure 4.1 notes that RGB components are returned as three separate integers between 0 and 255, submitted by address using ByRef Since passing by address is the default in VBA, the ByRef keyword can be omitted Because the procedure must return three values (r, g, and b) rather than a single value (as with theGrayColor() function), it is better implemented as a Sub.
• The main executable sub-routine Draw_FalseColorShades() uses the property.Interior.Colorand function RGB() with three different arguments r, g, and bto change the background color of cells.
As a result of executed procedureDraw_FalseColorShades(), 16 cells of row
1 in the active sheet are colored in suitable color shades corresponding to the position of the value i between Min = 1 and Max = 16 (from dark blue for i =1 to red fori= 16 –Fig 4.1).
The coordinate system of Excel cells is right-oriented, the X-axis points down, and the Y-axis points to the right.
Table 4.2 Sub-routines FalseColor() and Draw_FalseColorShades(), saved in Module1 in Ex04-02.xlsm
Sub FalseColor(ByVal Value#, ByVal Min#, ByVal Max#, ByRef r%, ByRef g%, ByRef b%) Dim c# c = (Value - Min) / (Max - Min)
ActiveSheet.Cells(1, i).Interior.Color = RGB(r, g, b)
Example 4.1.3 RGB definition and of false- and pseudo-colors with gamma correction
Gamma correction accounts for the nonlinear way the human eye perceives light, being less sensitive to bright highlights than to dark tones To ensure accurate colors on digital displays, gamma correction is applied to computer color values In most display systems, the encoding gamma is about 0.45 and the corresponding decoding gamma is about 2.2 The gamma value serves as the exponent that maps the color light intensity, expressed on a 0 to 1 scale, from black (0) to full brightness (1) After applying this correction, the resulting value is multiplied by 255 so it can be passed to the RGB() function.
Edit the function GrayColor() and procedure FalseColor() so that a gamma correction is applied to the generated gray and color shades.
Table 4.3 Function GrayColor_GammaCorrected(), procedures FalseColor_GammaCorrected (), and Draw_FalseColorShades_gamma_corrected(), saved in Module1 in Ex04-03.xlsm
Function GrayColor_GammaCorrected(ByVal Value#, ByVal Min#, ByVal Max#) As Integer
'gray color adjustment for visualization with public variable gamma_correction=0.45
Dim g# g = (Value - Min) / (Max - Min)
' color adjustment procedure for visualization
' set a public variable gamma_correction=0.45
Sub FalseColor_GammaCorrected(ByVal Value#, ByVal Min#, ByVal Max#, ByRef r%, ByRef g%, ByRef b%) Dim c#, rr#, gg#, bb# c = (Value - Min) / (Max - Min)
If c