I found myself often writing the same basic code while starting projects. I took a lot of the code and put it here for use. Below are the following included modules:

  • Word Document Creation (Python)
  • Importing, Exporting, and Modifying Excels (Python)
  • Basic HTML Example
  • VBA Values And Formulas
  • VBA Loop and Highlight
  • Complex WebDriver Example (No longer operational)
Word Document Creation (Python)

#Sample_Document_Creation.py

#The end of the code MUST be updated to a save path on the local computer

import docx
import os.path
from docx import Document
from docx.shared import Inches

#Create a different reference for document
document =  Document()

#This is the large heading at the top of the page
#The 0 determines the size of heading, it can range0-9
document.add_heading('Document Title', 0)

#Create a paragraph object: p. Then add text to it, having seperate lines for strings that should be bold or italicized
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

#Add another heading, the 'level=1' indicates the second largest heading. Simply having a 1 should work too.
document.add_heading('Heading, level 1', level=1)
#This paragraph shoes that there are many styles you can choose from
document.add_paragraph('Intense quote', style='Intense Quote')

#Two lists are created to show how its doene
document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
    'first item in ordered list', style='List Number'
)

#This creates a table. The records below give the content of the table but not the header
records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)

#This creates a new table, with ONLY the data descriptors filled out
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'

#This adds a row for each record of data. It first adds a row, and then fills out the three data points included
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

#adds page break
document.add_page_break()

#This saves the document to demo.docx in a specified spot
document.save("c:/users/Lyle Chamberlain/Documents/Example Python Modules/Word/Outputs/demo.docx")
Importing, Exporting, and Modifying Excels (Python)
#Importing_Exporting_Modifying_Excel.py

#User MUST update pathLocation or the code will not work on their local machines
import pandas as pd
import numpy as np


#Fuction that will return if a string is march (for demonstration purposes)
def isItMarch(monthValue):
    if monthValue == ('March'):
        return 'yep'
    else:
        return 'Nope'

def exportNewDF(df, fileName):
    #Gives location and name (myNewExcel) to exported file
    #Don't necesarily need to be two different lines but works better that way
    pathLocationOut = (r'c:\users\Lyle Chamberlain\Documents\Example Python Modules\Excel\Generated Outputs\myNewExcel.xls')
    df.to_excel(pathLocationOut)


#Gives location of file we're going to grab
pathLocation = (r'c:\users\Lyle Chamberlain\Documents\Example Python Modules\Excel\Environment_Temperature_change_E_All_Data_NOFLAG.xls')
#Read in excel
df = pd.read_excel(pathLocation)
rowCount = len(df)
#Just take first 50 rows), but all columns
df = df.iloc[0:50,]

#This is how to make an edit to each value
MarchOrNot = df.apply(
    #Lambda is used to make an edit for every row. In this case it passes the month of the row to the isItMarch Function
    lambda row: isItMarch(row['Months']), 
    #IMPORTANT, an axis of 1 will search row by row
    axis = 1
)

#Have the column labeled 'Area Code' contain the information returned by isItMarch
df['Area Code'] = MarchOrNot

#Use method toexport new df
exportNewDF(df, 'myTest')
Basic HTML Example
<!DOCTYPE html>

<html>
<!--Everything in the 'body' section will now be aligned center -->
<body align = "center">

<h1 title = "This is the title of the webpage"; align = "center">This is an h1 header</h1>

<p style ="color:green">This paragraph will be in green</p>

<style>
img {
  display: block;
  margin-left: auto;
  margin-right: auto;
}
</style>


<img src="https://www.cheatsheet.com/wp-content/uploads/2019/09/Mark-Cuban-1.jpg" alt="Paris" style="width:25%">

<button align = "center"> 
<a href = "https://www.w3schools.com/html/html_basic.asp"> click here for an HTML tutorial </a>
</button>

<ul style = "color:purple">
  <li>Did an un-numbered list</li>
  <li>Used Purple Font</li>
  <li>Glad it Worked</li>
</ul>

<hr>
<h3 style = "color:red">A slightly bigger title in Red </h3>
<ol style = "background-color: blue ; color:white">
  <li>Look I changed the Background Style</li>
  <li>Then created another list</li>
  <li>Not to bad</li>
</ol>

<p> Use a Line Break <br> To have text <br> jump down a line</p>


<pre style = "border:2px solid"> I made a border and used the pre
function to make it funky
</pre>

<style>
p,h1,ul,ol,h3,pre,img,button {
 text-align:center
 s
}
</style>



</body>
</html>
VBA Values and Formulas
'Sub indicates we are about to run the module named  'taxes_paid_on_401_taxsavings()

'If running multiple macros keep them on  the  same page and below 'the current Sub type 'Call ['Name of Sub']

Sub taxes_paid_on_401_taxsavings()
'
' A single quotation is a comment in VBA
' taxes_paid_on_401_withdrawal Macro
' This will find the taxes paid on the extra money you have due to 401k
'
' Keyboard Shortcut: Ctrl+a
'

'These are the taxes you're going to pay at yr 60 from that 401k withdrawal based on 1 year of 401k contributions



    'VBA requires that to refer to a cells contents, you must preface the reference with 'Range'
    'These Variables indicated by 'Set' allow us to avoid using Range each time
    'To avoid a user changing a column and destroying references, refer to cells by their names
    Set incomeAt60 = Range("D58")
    Set taxSavingsValue = Range("K10")
    Set taxesPaidAt60 = Range("AO58")
    Set taxesonContribution = Range("k11")
    Set valueof401kThroughContribution = Range("k9")
    
    
    'Find the income there so we don't mess it up
    startingIncome = incomeAt60.Value
    'Add income as if you were withdrawing tax savings
    newIncome = startingIncome + taxSavingsValue.Value + valueof401kThroughContribution.Value
    'Find the initial taxes paid so we can save
    startingTaxesPaid = taxesPaidAt60.Value
    startingTaxesFormula = taxesPaidAt60.Formula

    
    'Now change the income
    incomeAt60.Value = newIncome
    'Find the new taxes with new income
    newTaxes = taxesPaidAt60.Value
    'Find the difference (or taxes paid on the extra)
    taxIncrease = newTaxes - startingTaxesPaid
    'Put that tax increase into taxs paid on new 401
    taxesonContribution.Value = taxIncrease
    
    'Reset all statistics
    incomeAt60.Value = startingIncome
    'Check that starting taxes paidi is the same hopefully
    taxesPaidAt60.Formula = startingTaxesFormula
    
    
    


End Sub
VBA Loop and highlight
Sub FirstRecord()
'
' FirstRecord Macro
' This is my first recording I want to edit
'
' Keyboard Shortcut: Ctrl+i
'
    Dim firsty As Integer, secondy As Integer
    
    
    For firsty = 3 To 11
        secondy = Range("E" & firsty).Value
           If secondy > 0 Then

'Highlights colors by concatting a specified columnn and row given by firsty
                Range("E" & firsty).Interior.ColorIndex = 44
            ElseIf secondy = 0 Then
                Range("E" & firsty).Interior.ColorIndex = 25
                
            End If
                  

    
    Next firsty
    
    

    
End Sub
Complex WebDriver Example
import selenium
from selenium import webdriver
from lxml import etree
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import numpy as np
import pandas as pd
from selenium.webdriver.common.action_chains import ActionChains 
from selenium.webdriver.chrome.options import Options  
import os




#Create table of government vaccines
def createDataframe(vaccineData):
    vaccinedf = pd.read_excel(vaccineData)
    return vaccinedf

#not used at the moment
def createFullAddress(df):
    pass

def createDriver():
    #use chrome
    driver = webdriver.Chrome()

    #Open Webdriver
    driver.get('https://www.google.com/maps')
    return driver


def hitGoToButton():
    #hit goto
    goToButton = driver.find_element_by_id('searchbox-directions')
    goToButton.click()
    return

def hitGoToButton2():
    #hit goto
    #goToButton2 = driver.find_element_by_xpath('//div[@class = "searchbox-searchbutton"]')
    #goToButton2.click()
    action = ActionChains(driver) 
  
    # perform the oepration 
    action.key_down(Keys.RETURN).perform() 
    return

#puts in ending locaion 
def navigateMaps(start,end):
    #put cursor in search box
    searchBox = driver.find_element_by_name('q')

    #put in desired address to go to
    searchBox.send_keys(end)

    hitGoToButton()


    return

def findStartingAddressSearchBox():
    #Create while loop to allow map to load
    errorCounter = 0

    while(True):
        try:
            #this'll need to be changed
            if errorCounter < 1000000:
                errorCounter = errorCounter + 1
                inputStart = driver.find_element_by_xpath('//input[@placeholder="Choose starting point, or click on the map..."]')
                errorCounter = 0
                break
                return inputStart
            else: 
                break
        except:
            continue
        
    return inputStart

def findEndingAddress():
    #Create while loop to allow map to load
    errorCounter = 0

    while(True):
        try:
            if errorCounter < 1000000:
                errorCounter = errorCounter + 1
                endBox = driver.find_element_by_xpath('//input[@placeholder = ""]')
                errorCounter = 0
                break
                return endBox
            else: 
                return
        except:
            continue
    return endBox

def enterEndingAddress2(endbox, endingAddress):
    try:
        endbox.send_keys(endingAddress)
    except:
        endingAddress = 'Alaska'
        endbox.send_keys(endingAddress)
    return

def EnterStartingAddress(inputStart, startingAddress):
    #Send where to start navigation
    inputStart.send_keys(startingAddress)
    inputStart.send_keys(Keys.RETURN)
    return


def findDrivingMinutes():
    errorCounter = 0
    #trys to predict if the first one gest it or not
    nailedIt = 0
    #this allows us to pull the minutes it takes to get to the location
    while(True) and (nailedIt == 0):
        try:
            if errorCounter < 1000:
                errorCounter = errorCounter + 1
                minutes = driver.find_element_by_xpath('//div[@class = "section-directions-trip-duration delay-light"]').text
                nailedIt = 1
                break
            else: 
                break
        except:
            try:
                minutes = driver.find_element_by_xpath('//div[@class = "section-directions-trip-duration delay-medium"]').text
                nailedIt = 1
                break
            except:
                try:             
                    minutes = driver.find_element_by_xpath('//div[@class = "section-directions-trip-duration delay-heavy"]').text
                    nailedIt = 1
                    break
                except:
                    try: 
                        minutes = driver.find_element_by_xpath('//div[@class = "section-directions-trip-duration"]').text
                        nailedIt = 1
                    except:
                        continue

        if(errorCounter > 996):
            print("Input anything to continue")
            input()
            errorCounter = 0

     
    return minutes

def selectAllDelete():
    # create action chain object 
    action = ActionChains(driver) 
  
    # perform the oepration 
    action.key_down(Keys.CONTROL).send_keys('A').key_up(Keys.CONTROL).perform() 
    return

def hitSwitchLocations():
    switch = driver.find_element_by_xpath('//div[@class = "widget-directions-icon reverse"]')
    switch.click()
    return

def delay():
    wait = 0
    while(wait< 5000):
        wait = wait +1
    return

def ExportDF(df):
    pathLocationOut = (r'c:\users\Lyle Chamberlain\Downloads\VaccineShipments')
    df.to_excel(pathLocationOut)
    return

def extraDataColumns(VaccineData):
    VaccineData['Full Address'] = VaccineData['Street Address'] + ' ' + VaccineData['City']
    VaccineData['Hours'] = 'xxxx'
    VaccineData['Excess Minutes'] = 'xxxx'
    VaccineData['Total Minutes'] = 'xxxx'
    return VaccineData

def textToInt(VaccineData, index):

    stringy = VaccineData.at[index,'Driving Time String']

    #determine if there are any hours
    if('hr' in VaccineData.at[index,'Driving Time String']):
        VaccineData.at[index,'Hours'] = int(stringy[0])
        
        #fix for 2hr with no minutes
        try:
            newString = (stringy[5])+(stringy[6])
            VaccineData.at[index, 'Excess Minutes'] = int(newString)
        except:
            newString = 0
            VaccineData.at[index, 'Excess Minutes'] = int(newString)
        
        VaccineData.at[index, 'Total Minutes'] = (int(stringy[0])*60) +(int(newString))
   
   #if no hours excess minutes and total minutes are the same
    else:
        VaccineData.at[index,'Hours'] = 0
        VaccineData.at[index, 'Excess Minutes'] = stringy[0]+stringy[1]
        VaccineData.at[index, 'Total Minutes'] = stringy[0]+stringy[1]
        
    return VaccineData




#Create path to government vaccine deliveries
VaccineDataPath = (r'c:\Users\Lyle Chamberlain\Downloads\COVID-19 Vaccine_Provider_Locations_Week 13.xls')

#Create dataframe of vaccine data

VaccineData = createDataframe(VaccineDataPath)

VaccineData = pd.DataFrame(VaccineData)
VaccineData = extraDataColumns(VaccineData)
VaccineData['Driving Time String'] = ' hihi'

#create home address and ending address
startingAddress = '438 Birkel Avenue, Bethlehem, PA'
endingAddress = '250 Mall Blvd'

lastIndexCollected = 444

#Create driver instance


#options = webdriver.ChromeOptions()
#options.add_argument('--headless')
#options.add_argument('window-size=2000x1500')
driver = createDriver()

  

#lets us know we need to put in first iteration
firstTime = 1
breakEverything = 0


for index, row in VaccineData.iterrows():

    delay()
    if (firstTime == 1):
        #Don't come into this loop again
        firstTime = 0
        #enters values into start and end location
        navigateMaps(startingAddress, row['Full Address'])
        #finds box to put in initial starting box and enters it
        inputStart = findStartingAddressSearchBox()
        EnterStartingAddress(inputStart, startingAddress)
        #find minutes it takes to drive
        minutes = findDrivingMinutes()
       
       #save minutes into excel
        VaccineData.at[index,'Driving Time String'] = minutes

        

    #only hit switch locations once
    elif(firstTime == 0):
        checker = 0    
        hitSwitchLocations()
        
        while(True) and (checker < 100000):
            firstTime = 2
            #delete this and this  below it, won't belong in first take
            #used to have an input here
            endingAddressBox = findEndingAddress()
            endingAddressBox.click()
            selectAllDelete()
            enterEndingAddress2(endingAddressBox, row['Full Address'])
            hitGoToButton2()
            minutes = findDrivingMinutes()
            VaccineData.at[index,'Driving Time String'] = minutes
            if(minutes != VaccineData.at[(index-1), 'Driving Time String']):
                checker = 0
                break            


    else:
        if(index < lastIndexCollected):
            continue
        checker = 0
        while(True) and (checker < 1000000):
            checker = checker +1
            endingAddressBox = findEndingAddress()
            endingAddressBox.click()
            selectAllDelete()
            enterEndingAddress2(endingAddressBox, row['Full Address'])
            hitGoToButton2()
            try:
                delay()
                minutes = findDrivingMinutes()
            except:
                print("coulndn't find desired location, will give default value of 10hr Type qq to quit")
                myInput = input()
                if (myInput == 'qq'):
                    breakEverything = 1

                minutes = '10hr'

            VaccineData.at[index,'Driving Time String'] = minutes
            if(minutes != VaccineData.at[(index-1), 'Driving Time String']):
                checker = 0
                break

    textToInt(VaccineData,index)
    print("Time it takes to get to ", row['Full Address'], ' is ', minutes, ' index is ', index)

    if (breakEverything == 1):
        break

    

pathLocationOut = (r'c:\users\Lyle Chamberlain\Downloads\VaccineShipments.xls')
VaccineData.to_excel(pathLocationOut)