diff --git a/m language/M-Reference Language Tutorial - Accessing Data Sources.pq b/m language/M-Reference Language Tutorial - Accessing Data Sources.pq deleted file mode 100644 index 44f4da1..0000000 --- a/m language/M-Reference Language Tutorial - Accessing Data Sources.pq +++ /dev/null @@ -1,83 +0,0 @@ - -/* - - Working with data sources. - ---------------------------------------- - Inside Power Query and Power BI you'll be working with a variety of data sources, so it's important to know how to take your different files - and load them into these applications in the correct way. Depending on the type of file it is, the steps you take could be different, but - we will cover a few common scenarios for loading data. - -*/ - - - -let - - // The most basic thing we can do is grab all the BINARY CONTENT of a file. - myCSVFileContent = File.Contents("C:\Users\Alex\OneDrive\Desktop\korea_data.csv"), - - // Depending on the type of file it's coming from, we then pass it through the propert document function. In this case a Csv.Document function. - myCsvDocument = Csv.Document(myCSVFileContent, [Delimiter=",", Columns=11, Encoding=TextEncoding.Utf8, QuoteStyle=QuoteStyle.None]), - - /* - Normally you'll see the two steps up above in a single command, where the "File.Contents" function is found inside the document function. - - Source = Csv.Document(File.Contents("C:\Users\Alex\OneDrive\Desktop\korea_data.csv"),[Delimiter=",", Columns=11, Encoding=65001, QuoteStyle=QuoteStyle.None]) - */ - - //Let's grab an Excel workbook this time, first grab the content. - myExcelFileContent = File.Contents("C:\Users\Alex\OneDrive\Growth - Tutorial Videos\Lessons - VBA\balance_sheet_test.xlsx"), - - // Then pass it through the Excel.Workbook function. This particular document does not use a record to house paramaters. - myExcelFileDocument = Excel.Workbook(myExcelFileContent, true, true), - - /* - If you want the current workbook you're in, then do the following. - - Source = Excel.CurrentWorkbook() - - No arguments are needed. - */ - - - // However, content comes in many forms, we also have web pages. First we grab the web content. - myWebContent = Web.Contents("https://en.wikipedia.org/wiki/Star_Wars", [Timeout=#duration(0, 1, 40, 0)]), - - // Then pass it through the Web.Page function. Again, normally, these two steps are merged into one. - myWebPageContent = Web.Page(myWebPageContent), - - - - // Let's grab an acccess database. Because it's technially a file, we use the File.Contents first. - myAccessDatabaseContent = File.Contents("C:\Users\Alex\OneDrive\Career - Work Items\Petco\Financial_Analyst\Petco_Financial_Data.accdb"), - - // Then pass it through the proper document. - myAccessDatabase = Access.Database(myAccessDatabaseContent ,[CreateNavigationProperties=true]), - - // From here a new table is returned that has a structural representation of the database. If I want to grab a specific table I would do the following. - myAccessTable = myAccessDatabase{[Item = "ACTUALS_CAPITAL"]}[Data], // You can read this as return the row that has the column "Item" equal to "ACTUALS_CAPITAL" and then grab the "Data" column from that row. - - - // Let's grab an SQL Database, here I specify a Server, a Database, and set the HierarchicalNavigation to true and pass through a query. - mySQLDatabase= Sql.Database("DESKTOP-MOA8O6M\SQLEXPRESS", "stock_database", [HierarchicalNavigation=true, Query="SELECT * FROM [dbo].[td_service_data]"]), - - // Let's grab all the content of a folder. Where each row is either a file (binary) or folder (table) - myFolderContents = Folder.Contents("C:\Users\Alex\OneDrive\Growth - Tutorial Videos"), - - // Let's grab all the content of a JSON document. - myJsonDocument = Json.Document(File.Contents("C:\Users\Alex\OneDrive\Desktop\MyJsonDocument.json")), - - // Doesn't seem to be released yet? - myHTMLTable = Html.Table("Test", {{"Link", "a", each [Attributes][href]}}), - - // Grab all the Tables in PDF file - myPDFTables = Pdf.Tables(File.Contents("C:\Users\Alex\OneDrive\Desktop\Linear Regression Model.pdf")) - - // Let's wrap things up and make an API request. - myApiRequest = Json.Document(Web.Contents("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo")) - - -in - myApiRequest - - \ No newline at end of file diff --git a/m language/M-Reference Language Tutorial - Introduction.pq b/m language/M-Reference Language Tutorial - Introduction.pq deleted file mode 100644 index cdff8f2..0000000 --- a/m language/M-Reference Language Tutorial - Introduction.pq +++ /dev/null @@ -1,372 +0,0 @@ - -/* - - What is the M Formula Langague? - ---------------------------------------- - Microsoft Power Query provides a powerful data import experience that encompasses many features. Power Query works with - Analysis Services, Excel, and Power BI workbooks. A core capability of Power Query is to filter and combine, that is, to mash-up - data from one or more of a rich collection of supported data sources. Any such data mashup is expressed using the Power Query - M Formula Language. It's a functional, case sensitive language similar to F#. - - What is a M Formula Language Query? - ------------------------------------ - A Power Query M formula language query is composed of formula expression steps that create a mashup query. A formula expression - can be evaluated (computed), yielding a value. The let expression encapsulates a set of values to be computed, assigned names, - and then used in a subsequent expression that follows the in statement. - - Below is an example of a M Formula Language Query. - -*/ - - /* - Comment Structure - ------------------------------------ - */ - - /* Multi - Line - Comment */ - - // Single Line Comment - - -let - Source = Text.Proper("hello world.") -in - Source - - - -/* - - What is a Primitive Value? - ---------------------------------------- - A primitive value is single-part value, such as a number, logical, text, or null. - A null value can be used to indicate the absence of any data. - - Below is an example of the different primitive values. - -*/ - - - -let - - myBinary = #binary({0x30, 0x31, 0x32}), - myDate = #date(2015, 5, 23), - myDateTime = #datetime(2015, 5, 23, 0, 0 ,0), - myDateTimeZone = #datetimezone(2015, 5, 23, 0, 0 ,0, -8, 0), - myDuration = #duration(0, 15, 35, 0), - myLogical = true, - myNull = null, - myNumber = 0, - myText = "abc", - myTime = #time(12, 34, 12) - -in - myTime - - - -/* - - What is a Functional Value? - ---------------------------------------- - A Function is a value which, when invoked with arguments, produces a new value. Functions are written by - listing the function’s parameters in parentheses, followed by the goes-to symbol =>, followed by the expression defining the function. - - Below is an example of a functional value. - -*/ - - -let - // Define the function - MyFunction = (parameter1, parameter2) => (parameter1 + parameter2) / 2 , - - // call my function - Source = MyFunction(2, 4) - -in - Source - -/* - - What are Structured Data Values? - ---------------------------------------- - - List - -------------- - A List is a zero-based ordered sequence of values enclosed in curly brace characters { }. The curly brace characters { } - are also used to retrieve an item from a List by index position. See [List value](#_List_value). - - Power Query M supports an infinite list size, but if a list is written as a literal, the list has a fixed length. - For example, {1, 2, 3} has a fixed length of 3. - - - Record - ------------- - A Record is a set of fields. A field is a name/value pair where the name is a text value that is unique within the field’s - record. The syntax for record values allows the names to be written without quotes, a form also referred to as identifiers. - An identifier can take the following two forms: - - 1. identifier_name such as OrderID. - 2. #"identifier name" such as #"Today's data is: ". - - - Table - ------------ - A Table is a set of values organized into named columns and rows. The column type can be implicit or explicit. You can use - #table to create a list of column names and list of rows. A Table of values is a List in a List. The curly brace characters { } - are also used to retrieve a row from a Table by index position. - - -*/ - - -let - - myList = {"a", 100, false}, - myListOfNumbers = {1, 2, 3}, - myListOfLists = { - {1, 2, 3}, - {"a", "b", "c"}, - {true, false, true}, - {"a", 100, false} - }, - myListOfRecords = { - [CustomerID = 1, Name = "Bob", Phone = "123-4567"], - [CustomerID = 2, Name = "Jim", Phone = "987-6543"] - }, - myListIndexing = {"a", 100, false}{0}, /* returns "a" */ - myListIndexingNested = { - {1, 2, 3}, - {"a", "b", "c"}, - {true, false, true}, - {"a", 100, false} - }{0}{1} /* returns 2 */ - -in - myListIndexingNested - - -let - myRecord = [Name = "Alex", ID = 1111, Hometown = "San Diego"], - myRecordsNested = [Name = "Alex", ID = 1111, Hometown = "San Diego", Order = [ProductID = "ABC", Amount = 100.00]], - myName = myRecord[Name], - myAmount = myRecordsNested[Order][Amount] - -in - myAmount - - -let - myTable = #table( - {"OrderID", "CustomerID", "Item", "Price"}, /* My Column Names */ - {{1, 1, "Fishing rod", 100.00}, /* My Row 1 */ - {2, 1, "1 lb. worms", 5.00}} /* My Row 2 */ - ), - - myTableWithTypes = #table( - type table [OrderID = number, CustomerID = number, Item = text, Price = number], /* My Column Names With Defined Types */ - {{1, 1, "Fishing rod", 100.00}, /* My Row 1 */ - {2, 1, "1 lb. worms", 5.00}} /* My Row 2 */ - ), - - myTableRowOne = myTable{0} - -in - myTableRowOne - -/* - -TYPE CONVERSION ------------------------------------------------------------------------------------------------------------------------------------------------------- - -NUMBER ------- -Type conversion Description ---------------- ----------- -Number.FromText(text as text) as number Returns a number value from a text value. -Number.ToText(number as number) as text Returns a text value from a number value. -Number.From(value as any) as number Returns a number value from a value. -Int32.From(value as any) as number Returns a 32-bit integer number value from the given value. -Int64.From(value as any) as number Returns a 64-bit integer number value from the given value. -Single.From(value as any) as number Returns a Single number value from the given value. -Double.From(value as any) as number Returns a Double number value from the given value. -Decimal.From(value as any) as number Returns a Decimal number value from the given value. -Currency.From(value as any) as number Returns a Currency number value from the given value. - - -TEXT ------- -Type conversion Description ---------------- ----------- -Text.From(value as any) as text Returns the text representation of a number, date, time, datetime, datetimezone, logical, duration or binary value. - - -LOGICAL ------- -Type conversion Description ---------------- ----------- -Logical.FromText(text as text) as logical Returns a logical value of true or false from a text value. -Logical.ToText(logical as logical) as text Returns a text value from a logical value. -Logical.From(value as any) as logical Returns a logical value from a value. - - -DATE, TIME, DATETIME, AND DATE TIMEZONE ---------------------------------------- -Type conversion Description ---------------- ----------- -.FromText(text as text) as date, time, datetime, or datetimezone Returns a date, time, datetime, or datetimezone value from a set of date formats and culture value. -.ToText(date, time, dateTime, or dateTimeZone as date, time, datetime, or datetimezone) as text Returns a text value from a date, time, datetime, or datetimezone value. -.From(value as any) Returns a date, time, datetime, or datetimezone value from a value. -.ToRecord(date, time, dateTime, or dateTimeZone as date, time, datetime, or datetimezone) Returns a record containing parts of a date, time, datetime, or datetimezone value. - - -*/ - - - -/* - -OPERATORS ------------------------------------------------------------------------------------------------------------------------------------------------------- - - -Plus operator (+) ------------------------------- -Expression Equals -1 + 2 Numeric addition: 3 -#time(12,23,0) + #duration(0,0,2,0) Time arithmetic: #time(12,25,0) - - -Combination operator (&) ------------------------------- -Function Equals -"A" & "BC" Text concatenation: "ABC" -{1} & {2, 3} List concatenation: {1, 2, 3} -[ a = 1 ] & [ b = 2 ] Record merge: [ a = 1, b = 2 ] - - -List of M operators ------------------------------- - - -COMMON OPERATORS ------------------ -Common operators which apply to null, logical, number, time, date, datetime, datetimezone, duration, text, binary) - -Operator Description --------- ------------ -> Greater than ->= Greater than or equal -< Less than -<= Less than or equal -= Equal -<> Not equal - - -LOGICAL OPERATORS ------------------ - -Operator Description --------- ------------ -or Conditional logical OR -and Conditional logical AND -not Logical NOT - - -NUMBER OPERATORS ------------------ - -Operator Description --------- ------------ -+ Sum -- Difference -* Product -/ Quotient -+x Unary plus --x Negation - - -TEXT OPERATORS ------------------ - -Operator Description --------- ------------ -& Concatenation - - -LIST, RECORD, AND TABLE OPERATORS ------------------ - -Operator Description --------- ------------ -= Equal -<> Not equal -& Concatenation -[] Access the fields of a record by name. -{} Access an item in a list by its zero-based numeric index. - - -TYPE COMPATIABILITY AND ASSERTION OPERATORS ------------------ - -Operator Description --------- ------------ -is The expression x is y returns true if the type of x is compatible with y, and returns false if the type of x is not compatible with y. -as The expression x as y asserts that the value x is compatible with y as per the is operator. - - - -DATE OPERATORS ------------------ - -Operator Left Operand Right Operand Meaning ---------- ------------ ------------- ------- -x + y time duration Date offset by duration -x + y duration time Date offset by duration -x - y time duration Date offset by negated duration -x - y time time Duration between dates -x & y date time Merged datetime - - -DATETIME OPERATORS ------------------- - -Operator Left Operand Right Operand Meaning ---------- ------------ ------------- ------- -x + y datetime duration Datetime offset by duration -x + y duration datetime Datetime offset by duration -x - y datetime duration Datetime offset by negated duration -x - y datetime datetime Duration between datetimes - - -DATETIMEZONE OPERATORS ----------------------- - -Operator Left Operand Right Operand Meaning ---------- ------------ ------------- ------- -x + y datetimezone duration Datetimezone offset by duration -x + y duration datetimezone Datetimezone offset by duration -x - y datetimezone duration Datetimezone offset by negated duration -x - y datetimezone datetimezone Duration between datetimezones - - -DURATION OPERATORS ------------------- - -Operator Left Operand Right Operand Meaning ---------- ------------ ------------- ------- -x + y datetime duration Datetime offset by duration -x + y duration datetime Datetime offset by duration -x + y duration duration Sum of durations -x - y datetime duration Datetime offset by negated duration -x - y datetime datetime Duration between datetimes -x - y duration duration Difference of durations -x * y duration number N times a duration -x * y number duration N times a duration -x / y duration number Fraction of a duration - -*/ \ No newline at end of file diff --git a/m language/M-Reference Language Tutorial - Records.pq b/m language/M-Reference Language Tutorial - Records.pq deleted file mode 100644 index d1c6791..0000000 --- a/m language/M-Reference Language Tutorial - Records.pq +++ /dev/null @@ -1,96 +0,0 @@ - - -/* - What is a Record? - ----------------- - A Record is a set of fields. A field is a name/value pair where the name is a text value that is unique within the field’s - record. The syntax for record values allows the names to be written without quotes, a form also referred to as identifiers. - An identifier can take the following two forms: - - 1. identifier_name such as OrderID. - 2. #"identifier name" such as #"Today's data is: ". - -*/ - - -let - - // Lets define a new record, with 5 fields. - myRecord = [Name = "Alex", Age = 26, Gender = "Male", CollegeDegree = true, Salary = 1.00], - - // We can add a new field with Record.AddField function. - myRecordAddField = Record.AddField(myRecord, "Hometown","San Diego"), - - // We can remove a field with the Record.RemoveFields function. - myRecordRemoveField = Record.RemoveFields(myRecordAddField, "Gender"), // {"Gender", "Salary"} this will remove two fields Gender and Salary. - - // We can rename a field with the Record.RenameFields function. - myRecordRenamed = Record.RenameFields(myRecordRemoveField, {"Name", "FirstName"}), // {{"Salary", "SalaryCurr"}, {"Name", "FirstName"}} this will rename multiple fields. - - // We can reorder fields with the Record.ReorderFields function. - myRecordReordered = Record.ReorderFields(myRecordRenamed, {"FirstName", "Age", "CollegeDegree", "Hometown", "Salary"}), - - // We can combine two separate records with the Record.Combine function. - myRecordCombined = Record.Combine({myRecordReordered, [Birthday = "11/11/1992", FavoriteColor = "Blue"]}), // Notice that both records are wrapped in a list {} - - // We can transform the type of data each field has with the Record.TransformFields function. - myRecordTransformed = Record.TransformFields(myRecordCombined, {{"FirstName", Text.From}, - {"Age", Number.From}, - {"CollegeDegree", Logical.From}, - {"Hometown", Text.From}, - {"Salary", Decimal.From}, - {"Birthday", Date.FromText}, - {"FavoriteColor", Text.From}}), - - // We can grab all the field values with the Record.FieldValues function. - myRecordValues = Record.FieldValues(myRecordTransformed), - - // We can grab all the field names with the Record.FieldNames function. - myRecordFields = Record.FieldNames(myRecordTransformed), - - // We can select a fields in the following ways: - myName = myRecordTransformed[FirstName], - myAge = Record.Field(myRecordTransformed, "Age"), - myAgeAndName = Record.SelectFields(myRecordTransformed, {"Age", "FirstName"}), - - // We can check whether a field exists using the Record.HasFields function. - hasName = Record.HasFields(myRecordTransformed, "FirstName"), // true - hasNameAndFavoriteBook = Record.HasFields(myRecordTransformed, {"FirstName", "FavoriteBook"}), // {true, false} - - // We can convert a record to a list with Record.ToList function. - myRecordList = Record.ToList(myRecordTransformed), - - // We can convert a record to a table with the Record.ToTable function. - myRecordTable = Record.ToTable(myRecordTransformed), - - // We can try and access a field and if doesn't exist set what happens using the Record.FieldOrDefault function. - myNull = Record.FieldOrDefault(myRecordTransformed, "FavoriteBook"), // returns null as default. - myBook = Record.FieldOrDefault(myRecordTransformed, "FavoriteBook", "Star Wars"), // returns Star Wars as default. - - /* - - Enumeration Name Description - ----------- ---- ----------- - 0 MissingField.Error An optional parameter in record and table functions indicating that missing fields should result in an error. (This is the default parameter value.) - 1 MissingField.Ignore An optional parameter in record and table functions indicating that missing fields should be ignored. - 2 MissingField.UseNull An optional parameter in record and table functions indicating that missing fields should be included as null values. - - - In use it would look like the following: - - Expression: - ----------- - myAgeAndName = Record.SelectFields(myRecordTransformed, {"Age", "FavoriteBook"}, 2) - - Output: - ----------- - {26, null} as 2 represents MissingField.UseNull - - */ - - // Missing Fields Option Change Example - myAgeAndNameBehaviorChange = Record.SelectFields(myRecordTransformed, {"Age", "FavoriteBook"}, 2) - -in - - myAgeAndNameBehaviorChange \ No newline at end of file diff --git a/resources/javascript/Introduction to Office API - Asynchronous vs. Synchronous.pptx b/resources/javascript/Introduction to Office API - Asynchronous vs. Synchronous.pptx new file mode 100644 index 0000000..bc5e063 Binary files /dev/null and b/resources/javascript/Introduction to Office API - Asynchronous vs. Synchronous.pptx differ diff --git a/resources/javascript/Introduction to Office API - Introduction.pptx b/resources/javascript/Introduction to Office API - Introduction.pptx new file mode 100644 index 0000000..be2a7a3 Binary files /dev/null and b/resources/javascript/Introduction to Office API - Introduction.pptx differ diff --git a/resources/javascript/Introduction to Office API - Variable Declarations & Data Types.pptx b/resources/javascript/Introduction to Office API - Variable Declarations & Data Types.pptx new file mode 100644 index 0000000..148cb6b Binary files /dev/null and b/resources/javascript/Introduction to Office API - Variable Declarations & Data Types.pptx differ diff --git a/vba/advanced-vba/add-reference/Add References.bas b/vba/vba-advanced/add-reference/Add References.bas similarity index 100% rename from vba/advanced-vba/add-reference/Add References.bas rename to vba/vba-advanced/add-reference/Add References.bas diff --git a/vba/excel-vba/adodb-library/Connect To Access Database.bas b/vba/vba-advanced/adodb-library/Connect To Access Database.bas similarity index 96% rename from vba/excel-vba/adodb-library/Connect To Access Database.bas rename to vba/vba-advanced/adodb-library/Connect To Access Database.bas index 2dab1f4..70614cb 100644 --- a/vba/excel-vba/adodb-library/Connect To Access Database.bas +++ b/vba/vba-advanced/adodb-library/Connect To Access Database.bas @@ -1,48 +1,48 @@ -Option Explicit - -Sub ExportDataToAccess() - - Dim ConnObj As ADODB.Connection - Dim RecSet As ADODB.Recordset - Dim ConnCmd As ADODB.Command - Dim ColNames As ADODB.Fields - Dim DataSource As String - Dim intLoop As Integer - - 'Define the data source - DataSource = "C:\Users\Alex\Desktop\Financial_Data.accdb" - - 'Create a new connection object & a new command object - Set ConnObj = New ADODB.Connection - Set ConnCmd = New ADODB.Command - - 'Create a new connection - With ConnObj - .Provider = "Microsoft.ACE.OLEDB.12.0" 'For *.ACCDB Databases - .ConnectionString = DataSource - .Open - End With - - 'This will allow the command object to use the Active Connection - ConnCmd.ActiveConnection = ConnObj - - 'Define the Query String & the Query Type. - ConnCmd.CommandText = "SELECT * FROM ACTUALS_CAPITAL;" - ConnCmd.CommandType = adCmdText - - 'Exectue the Query & Get the column Names. - Set RecSet = ConnCmd.Execute - Set ColNames = RecSet.Fields - - 'Populate the header row of the Excel Sheet. - For intLoop = 0 To ColNames.Count - 1 - Cells(1, intLoop + 1).Value = ColNames.Item(intLoop).Name - Next - - 'Dump the data in the worksheet. - Range("A2").CopyFromRecordset RecSet - - 'Close the Connection - ConnObj.Close - -End Sub +Option Explicit + +Sub ExportDataToAccess() + + Dim ConnObj As ADODB.Connection + Dim RecSet As ADODB.Recordset + Dim ConnCmd As ADODB.Command + Dim ColNames As ADODB.Fields + Dim DataSource As String + Dim intLoop As Integer + + 'Define the data source + DataSource = "C:\Users\Alex\Desktop\Financial_Data.accdb" + + 'Create a new connection object & a new command object + Set ConnObj = New ADODB.Connection + Set ConnCmd = New ADODB.Command + + 'Create a new connection + With ConnObj + .Provider = "Microsoft.ACE.OLEDB.12.0" 'For *.ACCDB Databases + .ConnectionString = DataSource + .Open + End With + + 'This will allow the command object to use the Active Connection + ConnCmd.ActiveConnection = ConnObj + + 'Define the Query String & the Query Type. + ConnCmd.CommandText = "SELECT * FROM ACTUALS_CAPITAL;" + ConnCmd.CommandType = adCmdText + + 'Exectue the Query & Get the column Names. + Set RecSet = ConnCmd.Execute + Set ColNames = RecSet.Fields + + 'Populate the header row of the Excel Sheet. + For intLoop = 0 To ColNames.Count - 1 + Cells(1, intLoop + 1).Value = ColNames.Item(intLoop).Name + Next + + 'Dump the data in the worksheet. + Range("A2").CopyFromRecordset RecSet + + 'Close the Connection + ConnObj.Close + +End Sub diff --git a/vba/advanced-vba/commandbar-object/Commandbar Object.bas b/vba/vba-advanced/commandbar-object/Commandbar Object.bas similarity index 100% rename from vba/advanced-vba/commandbar-object/Commandbar Object.bas rename to vba/vba-advanced/commandbar-object/Commandbar Object.bas diff --git a/vba/advanced-vba/commandbar-object/CommandbarControls Object.bas b/vba/vba-advanced/commandbar-object/CommandbarControls Object.bas similarity index 100% rename from vba/advanced-vba/commandbar-object/CommandbarControls Object.bas rename to vba/vba-advanced/commandbar-object/CommandbarControls Object.bas diff --git a/vba/advanced-vba/create-zipped-folder/Create Zipped Folders.bas b/vba/vba-advanced/create-zipped-folder/Create Zipped Folders.bas similarity index 100% rename from vba/advanced-vba/create-zipped-folder/Create Zipped Folders.bas rename to vba/vba-advanced/create-zipped-folder/Create Zipped Folders.bas diff --git a/vba/advanced-vba/export-macros/Export Macros.bas b/vba/vba-advanced/export-macros/Export Macros.bas similarity index 100% rename from vba/advanced-vba/export-macros/Export Macros.bas rename to vba/vba-advanced/export-macros/Export Macros.bas diff --git a/vba/excel-vba/file-system-object/File System Object.bas b/vba/vba-advanced/file-system-object/File System Object.bas similarity index 100% rename from vba/excel-vba/file-system-object/File System Object.bas rename to vba/vba-advanced/file-system-object/File System Object.bas diff --git a/vba/advanced-vba/python-from-excel/Run Python Script.bas b/vba/vba-advanced/python-from-excel/Run Python Script.bas similarity index 100% rename from vba/advanced-vba/python-from-excel/Run Python Script.bas rename to vba/vba-advanced/python-from-excel/Run Python Script.bas diff --git a/vba/advanced-vba/scripting-automation-library/Scripting Automation.bas b/vba/vba-advanced/scripting-automation-library/Scripting Automation.bas similarity index 100% rename from vba/advanced-vba/scripting-automation-library/Scripting Automation.bas rename to vba/vba-advanced/scripting-automation-library/Scripting Automation.bas diff --git a/vba/advanced-vba/user-forms/export-manager/Export Manager.bas b/vba/vba-advanced/user-forms/export-manager/Export Manager.bas similarity index 100% rename from vba/advanced-vba/user-forms/export-manager/Export Manager.bas rename to vba/vba-advanced/user-forms/export-manager/Export Manager.bas diff --git a/vba/advanced-vba/user-forms/sql-query/SQLQueryForm.frm b/vba/vba-advanced/user-forms/sql-query/SQLQueryForm.frm similarity index 100% rename from vba/advanced-vba/user-forms/sql-query/SQLQueryForm.frm rename to vba/vba-advanced/user-forms/sql-query/SQLQueryForm.frm diff --git a/vba/advanced-vba/user-forms/sql-query/SQLQueryForm.frx b/vba/vba-advanced/user-forms/sql-query/SQLQueryForm.frx similarity index 100% rename from vba/advanced-vba/user-forms/sql-query/SQLQueryForm.frx rename to vba/vba-advanced/user-forms/sql-query/SQLQueryForm.frx diff --git a/vba/advanced-vba/user-forms/sql-query/UserFormSql.bas b/vba/vba-advanced/user-forms/sql-query/UserFormSql.bas similarity index 100% rename from vba/advanced-vba/user-forms/sql-query/UserFormSql.bas rename to vba/vba-advanced/user-forms/sql-query/UserFormSql.bas diff --git a/vba/advanced-vba/visual-basic-editor/visual-basic-editor.vb b/vba/vba-advanced/visual-basic-editor/visual-basic-editor.vb similarity index 100% rename from vba/advanced-vba/visual-basic-editor/visual-basic-editor.vb rename to vba/vba-advanced/visual-basic-editor/visual-basic-editor.vb diff --git a/vba/advanced-vba/web-scraping/Webscraping.bas b/vba/vba-advanced/web-scraping/Webscraping.bas similarity index 100% rename from vba/advanced-vba/web-scraping/Webscraping.bas rename to vba/vba-advanced/web-scraping/Webscraping.bas diff --git a/vba/advanced-vba/web-scraping/WebscrapingTables.bas b/vba/vba-advanced/web-scraping/WebscrapingTables.bas similarity index 100% rename from vba/advanced-vba/web-scraping/WebscrapingTables.bas rename to vba/vba-advanced/web-scraping/WebscrapingTables.bas diff --git a/vba/advanced-vba/xml-library/JsonConverter.bas b/vba/vba-advanced/xml-library/JsonConverter.bas similarity index 100% rename from vba/advanced-vba/xml-library/JsonConverter.bas rename to vba/vba-advanced/xml-library/JsonConverter.bas diff --git a/vba/advanced-vba/xml-library/Requesting APIs - JSON.bas b/vba/vba-advanced/xml-library/Requesting APIs - JSON.bas similarity index 100% rename from vba/advanced-vba/xml-library/Requesting APIs - JSON.bas rename to vba/vba-advanced/xml-library/Requesting APIs - JSON.bas diff --git a/vba/advanced-vba/xml-library/Requesting APIs - XML.bas b/vba/vba-advanced/xml-library/Requesting APIs - XML.bas similarity index 100% rename from vba/advanced-vba/xml-library/Requesting APIs - XML.bas rename to vba/vba-advanced/xml-library/Requesting APIs - XML.bas diff --git a/vba/excel-vba/core-concepts/Case Statements.bas b/vba/vba-core/Conditions - Case Statements.bas similarity index 96% rename from vba/excel-vba/core-concepts/Case Statements.bas rename to vba/vba-core/Conditions - Case Statements.bas index 38d17ae..3b69936 100644 --- a/vba/excel-vba/core-concepts/Case Statements.bas +++ b/vba/vba-core/Conditions - Case Statements.bas @@ -1,209 +1,209 @@ -Attribute VB_Name = "Module1" -Option Explicit - -Sub CaseStatements() - - 'Declare Variable - Dim DayOfWeek As String - - 'Select the starting cell - ActiveSheet.Range("B3").Select - - 'Create a do while loop that will loop through the range of cells. - Do While ActiveCell.Value <> "" - - 'Set my variable equal to active cell value on each iteration of the loop - DayOfWeek = ActiveCell.Value - - 'Create the case statement - Select Case DayOfWeek - - Case "monday" - ActiveCell.Offset(0, 1).Value = "Good" - - Case "Tuesday" - ActiveCell.Offset(0, 1).Value = "Good" - - Case "Wednesday" - ActiveCell.Offset(0, 1).Value = "Good" - - Case "Thursday" - ActiveCell.Offset(0, 1).Value = "Bad" - - Case "Friday" - ActiveCell.Offset(0, 1).Value = "Bad" - - Case "Saturday" - ActiveCell.Offset(0, 1).Value = "Good" - - Case "Sunday" - ActiveCell.Offset(0, 1).Value = "Neutral" - - End Select - - 'GO TO THE NEXT CELL --- VERY IMPORTANT - ActiveCell.Offset(1, 0).Select - - Loop - -End Sub - -Sub CaseStatements_Operator() - - 'Declare Variable - Dim DayOfWeek As String - - 'Select the starting cell - ActiveSheet.Range("B3").Select - - 'Create a do while loop that will loop through the range of cells. - Do While ActiveCell.Value <> "" - - 'Set my variable equal to active cell value on each iteration of the loop - DayOfWeek = ActiveCell.Value - - 'Create the case statement - Select Case DayOfWeek - - Case "Monday", "Tuesday", "Wednesday", "Saturday" - ActiveCell.Offset(0, 1).Value = "Good" - - Case "Thursday", "Friday" - ActiveCell.Offset(0, 1).Value = "Bad" - - Case "Sunday" - ActiveCell.Offset(0, 1).Value = "Neutral" - - End Select - - 'GO TO THE NEXT CELL --- VERY IMPORTANT - ActiveCell.Offset(1, 0).Select - - Loop - -End Sub - - -Sub CaseStatements_Else() - - 'Declare Variable - Dim DayOfWeek As String - - 'Select the starting cell - ActiveSheet.Range("B3").Select - - 'Create a do while loop that will loop through the range of cells. - Do While ActiveCell.Value <> "" - - 'Set my variable equal to active cell value on each iteration of the loop - DayOfWeek = ActiveCell.Value - - 'Create the case statement - Select Case DayOfWeek - - Case "Monday", "Tuesday", "Wednesday", "Saturday" - ActiveCell.Offset(0, 1).Value = "Good" - - Case "Thursday", "Friday" - ActiveCell.Offset(0, 1).Value = "Bad" - - Case "Sunday" - ActiveCell.Offset(0, 1).Value = "Neutral" - - Case Else - ActiveCell.Offset(0, 1).Value = "You Messed Up Big Time" - - End Select - - 'GO TO THE NEXT CELL --- VERY IMPORTANT - ActiveCell.Offset(1, 0).Select - - Loop - -End Sub - - -Sub CaseStatements_Range() - - 'We use IS keyword with comparison operators - 'We use TO keyword with a range of values - - 'Declare Variable - Dim DayOfWeek As String - Dim DayScore As Variant - - 'Select the starting cell - ActiveSheet.Range("D3").Select - - 'Create a do while loop that will loop through the range of cells. - Do While ActiveCell.Value <> "" - - 'Set my variable equal to active cell value on each iteration of the loop - DayScore = ActiveCell.Value - - 'Create the case statement - Select Case DayScore - - Case Is > 90 - ActiveCell.Offset(0, 1).Value = "A" - - Case 79 To 90 - ActiveCell.Offset(0, 1).Value = "B" - - Case 69 To 78 - ActiveCell.Offset(0, 1).Value = "C" - - Case 59 To 68 - ActiveCell.Offset(0, 1).Value = "D" - - Case Is < 58 - ActiveCell.Offset(0, 1).Value = "F" - - Case Else - ActiveCell.Offset(0, 1).Value = "You Messed Up Big Time" - - End Select - - 'GO TO THE NEXT CELL --- VERY IMPORTANT - ActiveCell.Offset(1, 0).Select - - Loop - -End Sub - - -Sub CaseStatements_Strings() - - 'Declare Variable - Dim DayOfWeek As String - - 'Select the starting cell - ActiveSheet.Range("B3").Select - - 'Create a do while loop that will loop through the range of cells. - Do While ActiveCell.Value <> "" - - 'Set my variable equal to active cell value on each iteration of the loop - DayOfWeek = ActiveCell.Value - - 'Create the case statement - Select Case DayOfWeek - - 'Any value that falls within the alphabetical range - Case "Monday" To "Saturday" - ActiveCell.Offset(0, 1).Value = "Good" - - Case "Sunday" - ActiveCell.Offset(0, 1).Value = "Ok Good" - - Case Else - ActiveCell.Offset(0, 1).Value = "You Messed Up Big Time" - - End Select - - 'GO TO THE NEXT CELL --- VERY IMPORTANT - ActiveCell.Offset(1, 0).Select - - Loop - -End Sub +Attribute VB_Name = "Module1" +Option Explicit + +Sub CaseStatements() + + 'Declare Variable + Dim DayOfWeek As String + + 'Select the starting cell + ActiveSheet.Range("B3").Select + + 'Create a do while loop that will loop through the range of cells. + Do While ActiveCell.Value <> "" + + 'Set my variable equal to active cell value on each iteration of the loop + DayOfWeek = ActiveCell.Value + + 'Create the case statement + Select Case DayOfWeek + + Case "monday" + ActiveCell.Offset(0, 1).Value = "Good" + + Case "Tuesday" + ActiveCell.Offset(0, 1).Value = "Good" + + Case "Wednesday" + ActiveCell.Offset(0, 1).Value = "Good" + + Case "Thursday" + ActiveCell.Offset(0, 1).Value = "Bad" + + Case "Friday" + ActiveCell.Offset(0, 1).Value = "Bad" + + Case "Saturday" + ActiveCell.Offset(0, 1).Value = "Good" + + Case "Sunday" + ActiveCell.Offset(0, 1).Value = "Neutral" + + End Select + + 'GO TO THE NEXT CELL --- VERY IMPORTANT + ActiveCell.Offset(1, 0).Select + + Loop + +End Sub + +Sub CaseStatements_Operator() + + 'Declare Variable + Dim DayOfWeek As String + + 'Select the starting cell + ActiveSheet.Range("B3").Select + + 'Create a do while loop that will loop through the range of cells. + Do While ActiveCell.Value <> "" + + 'Set my variable equal to active cell value on each iteration of the loop + DayOfWeek = ActiveCell.Value + + 'Create the case statement + Select Case DayOfWeek + + Case "Monday", "Tuesday", "Wednesday", "Saturday" + ActiveCell.Offset(0, 1).Value = "Good" + + Case "Thursday", "Friday" + ActiveCell.Offset(0, 1).Value = "Bad" + + Case "Sunday" + ActiveCell.Offset(0, 1).Value = "Neutral" + + End Select + + 'GO TO THE NEXT CELL --- VERY IMPORTANT + ActiveCell.Offset(1, 0).Select + + Loop + +End Sub + + +Sub CaseStatements_Else() + + 'Declare Variable + Dim DayOfWeek As String + + 'Select the starting cell + ActiveSheet.Range("B3").Select + + 'Create a do while loop that will loop through the range of cells. + Do While ActiveCell.Value <> "" + + 'Set my variable equal to active cell value on each iteration of the loop + DayOfWeek = ActiveCell.Value + + 'Create the case statement + Select Case DayOfWeek + + Case "Monday", "Tuesday", "Wednesday", "Saturday" + ActiveCell.Offset(0, 1).Value = "Good" + + Case "Thursday", "Friday" + ActiveCell.Offset(0, 1).Value = "Bad" + + Case "Sunday" + ActiveCell.Offset(0, 1).Value = "Neutral" + + Case Else + ActiveCell.Offset(0, 1).Value = "You Messed Up Big Time" + + End Select + + 'GO TO THE NEXT CELL --- VERY IMPORTANT + ActiveCell.Offset(1, 0).Select + + Loop + +End Sub + + +Sub CaseStatements_Range() + + 'We use IS keyword with comparison operators + 'We use TO keyword with a range of values + + 'Declare Variable + Dim DayOfWeek As String + Dim DayScore As Variant + + 'Select the starting cell + ActiveSheet.Range("D3").Select + + 'Create a do while loop that will loop through the range of cells. + Do While ActiveCell.Value <> "" + + 'Set my variable equal to active cell value on each iteration of the loop + DayScore = ActiveCell.Value + + 'Create the case statement + Select Case DayScore + + Case Is > 90 + ActiveCell.Offset(0, 1).Value = "A" + + Case 79 To 90 + ActiveCell.Offset(0, 1).Value = "B" + + Case 69 To 78 + ActiveCell.Offset(0, 1).Value = "C" + + Case 59 To 68 + ActiveCell.Offset(0, 1).Value = "D" + + Case Is < 58 + ActiveCell.Offset(0, 1).Value = "F" + + Case Else + ActiveCell.Offset(0, 1).Value = "You Messed Up Big Time" + + End Select + + 'GO TO THE NEXT CELL --- VERY IMPORTANT + ActiveCell.Offset(1, 0).Select + + Loop + +End Sub + + +Sub CaseStatements_Strings() + + 'Declare Variable + Dim DayOfWeek As String + + 'Select the starting cell + ActiveSheet.Range("B3").Select + + 'Create a do while loop that will loop through the range of cells. + Do While ActiveCell.Value <> "" + + 'Set my variable equal to active cell value on each iteration of the loop + DayOfWeek = ActiveCell.Value + + 'Create the case statement + Select Case DayOfWeek + + 'Any value that falls within the alphabetical range + Case "Monday" To "Saturday" + ActiveCell.Offset(0, 1).Value = "Good" + + Case "Sunday" + ActiveCell.Offset(0, 1).Value = "Ok Good" + + Case Else + ActiveCell.Offset(0, 1).Value = "You Messed Up Big Time" + + End Select + + 'GO TO THE NEXT CELL --- VERY IMPORTANT + ActiveCell.Offset(1, 0).Select + + Loop + +End Sub diff --git a/vba/excel-vba/core-concepts/If Statements.bas b/vba/vba-core/Conditions - If Statements.bas similarity index 95% rename from vba/excel-vba/core-concepts/If Statements.bas rename to vba/vba-core/Conditions - If Statements.bas index b987071..fc871fc 100644 --- a/vba/excel-vba/core-concepts/If Statements.bas +++ b/vba/vba-core/Conditions - If Statements.bas @@ -1,166 +1,166 @@ -Sub IfThen() - - 'Declare a variable that will house the test score. - Dim TestScore As Integer - - 'Set the variable equal the value of cell "C3". - TestScore = Range("C3").Value - - 'Begin if statement - If TestScore = 75 Then - Range("D3").Value = "C" - End If - -End Sub - -Sub IfThenElse() - - 'Declare a variable that will house the test score. - Dim TestScore As Integer - - 'Set the variable equal the value of cell "C3". - TestScore = Range("C3").Value - - 'Begin if statement - If TestScore = 75 Then - Range("D3").Value = "C" - Else - Range("D3").Value = "No Score Provided" - End If - -End Sub - -Sub IfThenElseIfElse() - - 'Declare a variable that will house the test score. - Dim TestScore As Integer - - 'Set the variable equal the value of cell "C3". - TestScore = Range("C3").Value - - 'Begin if statement - If TestScore = 75 Then - Range("D3").Value = "C" - - ElseIf TestScore = 85 Then - Range("D3").Value = "B" - - Else - Range("D3").Value = "No Score Provided" - End If - -End Sub - -Sub NestedIfStatements() - - 'Declare a variable that will house the test score & Favorite Color. - Dim TestScore As Integer - Dim FavrColor As String - - 'Store values in variables - TestScore = Range("H3").Value - FavrColor = Range("G3").Value - - 'Begin if statement - If TestScore = 75 Then - - 'Nested If Statement - If FavrColor = "Blue" Then - Range("I3").Value = "Great" - Else - Range("I3").Value = "Wonderful" - End If - - ElseIf TestScore = 85 Then - - 'Nested If Statement - If FavrColor = "Red" Then - Range("I3").Value = "Not Great" - Else - Range("I3").Value = "Not Wonderful" - End If - - Else - Range("I3").Value = "No Score Provided" - End If - -End Sub - -Sub IfStatementsWithLogicalOperators() - - 'Declare a variable that will house the test score & Favorite Color. - Dim TestScore As Integer - Dim FavrColor As String - - 'Store values in variables - TestScore = Range("H3").Value - FavrColor = Range("G3").Value - - 'Begin if statement - If TestScore = 75 And FavrColor = "Blue" Then - Range("I3").Value = "Great" - - 'ElseIf Section One - ElseIf TestScore = 75 And FavrColor = "Red" Then - Range("I3").Value = "Wonderful" - - 'ElseIf Section Two - ElseIf TestScore = 85 And FavrColor = "Blue" Then - Range("I3").Value = "Not Great" - - 'ElseIf Section Three - ElseIf TestScore = 85 And FavrColor = "Red" Then - Range("I3").Value = "Not Wonderful" - - 'Else Section - Else - Range("I3").Value = "No Score Provided" - - 'Close If Block - End If - -End Sub - -Sub WrongIfStatement() - - 'Declare a variable that will house the test score & Favorite Color. - Dim TestScore As Integer - - 'Store values in variables - TestScore = Range("H3").Value - - 'This is incorrect because the Else If will never be reached. - If TestScore >= 75 Then - Range("I3").Value = "Great" - - ElseIf TestScore >= 85 Then - 'This Portion of the code would never be reached. - Range("I3").Value = "Wonderful" - - End If - -End Sub - -Sub UsingProperties() - - 'Declare a variable that will house the test score & Favorite Color. - Dim Rng As Range - - 'Store values in variables - Set Rng = Range("H3:H5") - - 'This is incorrect because the Else If will never be reached. - If Rng.Count = 1 Then - MsgBox "You have one cell!" - - ElseIf Rng.Count > 1 Then - 'This Portion of the code would never be reached. - MsgBox "You have more than one cell!" - - Else - 'This Portion of the code would never be reached. - MsgBox "Make sure to select a range in order to use this macro." - - End If - -End Sub +Sub IfThen() + + 'Declare a variable that will house the test score. + Dim TestScore As Integer + + 'Set the variable equal the value of cell "C3". + TestScore = Range("C3").Value + + 'Begin if statement + If TestScore = 75 Then + Range("D3").Value = "C" + End If + +End Sub + +Sub IfThenElse() + + 'Declare a variable that will house the test score. + Dim TestScore As Integer + + 'Set the variable equal the value of cell "C3". + TestScore = Range("C3").Value + + 'Begin if statement + If TestScore = 75 Then + Range("D3").Value = "C" + Else + Range("D3").Value = "No Score Provided" + End If + +End Sub + +Sub IfThenElseIfElse() + + 'Declare a variable that will house the test score. + Dim TestScore As Integer + + 'Set the variable equal the value of cell "C3". + TestScore = Range("C3").Value + + 'Begin if statement + If TestScore = 75 Then + Range("D3").Value = "C" + + ElseIf TestScore = 85 Then + Range("D3").Value = "B" + + Else + Range("D3").Value = "No Score Provided" + End If + +End Sub + +Sub NestedIfStatements() + + 'Declare a variable that will house the test score & Favorite Color. + Dim TestScore As Integer + Dim FavrColor As String + + 'Store values in variables + TestScore = Range("H3").Value + FavrColor = Range("G3").Value + + 'Begin if statement + If TestScore = 75 Then + + 'Nested If Statement + If FavrColor = "Blue" Then + Range("I3").Value = "Great" + Else + Range("I3").Value = "Wonderful" + End If + + ElseIf TestScore = 85 Then + + 'Nested If Statement + If FavrColor = "Red" Then + Range("I3").Value = "Not Great" + Else + Range("I3").Value = "Not Wonderful" + End If + + Else + Range("I3").Value = "No Score Provided" + End If + +End Sub + +Sub IfStatementsWithLogicalOperators() + + 'Declare a variable that will house the test score & Favorite Color. + Dim TestScore As Integer + Dim FavrColor As String + + 'Store values in variables + TestScore = Range("H3").Value + FavrColor = Range("G3").Value + + 'Begin if statement + If TestScore = 75 And FavrColor = "Blue" Then + Range("I3").Value = "Great" + + 'ElseIf Section One + ElseIf TestScore = 75 And FavrColor = "Red" Then + Range("I3").Value = "Wonderful" + + 'ElseIf Section Two + ElseIf TestScore = 85 And FavrColor = "Blue" Then + Range("I3").Value = "Not Great" + + 'ElseIf Section Three + ElseIf TestScore = 85 And FavrColor = "Red" Then + Range("I3").Value = "Not Wonderful" + + 'Else Section + Else + Range("I3").Value = "No Score Provided" + + 'Close If Block + End If + +End Sub + +Sub WrongIfStatement() + + 'Declare a variable that will house the test score & Favorite Color. + Dim TestScore As Integer + + 'Store values in variables + TestScore = Range("H3").Value + + 'This is incorrect because the Else If will never be reached. + If TestScore >= 75 Then + Range("I3").Value = "Great" + + ElseIf TestScore >= 85 Then + 'This Portion of the code would never be reached. + Range("I3").Value = "Wonderful" + + End If + +End Sub + +Sub UsingProperties() + + 'Declare a variable that will house the test score & Favorite Color. + Dim Rng As Range + + 'Store values in variables + Set Rng = Range("H3:H5") + + 'This is incorrect because the Else If will never be reached. + If Rng.Count = 1 Then + MsgBox "You have one cell!" + + ElseIf Rng.Count > 1 Then + 'This Portion of the code would never be reached. + MsgBox "You have more than one cell!" + + Else + 'This Portion of the code would never be reached. + MsgBox "Make sure to select a range in order to use this macro." + + End If + +End Sub diff --git a/vba/excel-vba/core-concepts/Data Types.bas b/vba/vba-core/Data Types - All.bas similarity index 95% rename from vba/excel-vba/core-concepts/Data Types.bas rename to vba/vba-core/Data Types - All.bas index a201f6e..e57225c 100644 --- a/vba/excel-vba/core-concepts/Data Types.bas +++ b/vba/vba-core/Data Types - All.bas @@ -1,224 +1,224 @@ -Attribute VB_Name = "DataTypes" -Sub DataTypes() - - 'Name: Variant - 'Allocation: 16 to 22 bytes - 'Range: N/A - - 'Declare Variables with Variant Data Type - Dim EmptyValue As Variant - Dim ErrorValue As Variant - Dim NothingValue As Variant - Dim NullValue As Variant - - 'This means that no value has been assigned to the variable. - EmptyValue = Empty - - 'Error help us for identifying errors in our procedure. - ErrorValue = Error - - 'Nothing is the uninitialized state of an object variable. - Set NothingValue = Nothing - - 'This indicates that the variable is absent of data. - NullValue = Null - -End Sub - -Sub ByteDataType() - - 'Name: Byte - 'Allocation: 1 Bytes - 'Range: 0 to 255 - - Dim ByteValue As Byte - ByteValue = 100 - -End Sub - -Sub BooleanDataType() - - 'Name: Boolean - 'Allocation: 2 Bytes - 'Range: True or False - - Dim BooleanValue As Boolean - BooleanValue = True - BooleanValue = False - -End Sub - - -Sub CurrencyDataType() - - 'Name: Currency - 'Allocation: 8 Bytes - 'Range: -922,337,203,685,477.5808 and 922,337,203,685,477.5807 - - Dim CurrencyValue As Currency - CurrencyValue = 200000000 - - 'Using Character Type Method - CurrencyValue2@ = 200000000 - -End Sub - -Sub DateDataType() - - 'Name: Date - 'Allocation: 8 Bytes - 'Range Dates: Dates between January 1, 100 and December 31, 9999 - 'Range Times: Times between midnight (00:00:00) and 23:59:59 - - Dim DateValue As Date - DateValueSerial = 43435 '<<< This is 12/1/2018 - DateValueLiteral = #12/1/2018# - - TimeValueSerial = 0.54 '<<< This is 1:00:00PM - TimeValueLiteral = #1:00:00 PM# - - DateTimeValueSerial = 43435.54 '<<< This is 12/1/2018 1:00:00 PM - DateTimeValueLiteral = #12/1/2018 1:00:00 PM# - - DateValueSerialNeg = -1 '<<< This is 12/30/1899 - -End Sub - -Sub DecimalDataType() - - 'Name: Decimal - 'Allocation: 14 Byte - 'Range: +/-79,228,162,514,264,337,593,543,950,335 with no decial point / +/-7.9228162514264337593543950335 with 28 places to the right of the decimal - - Dim DeciVal As Variant - DeciVal = 1.15 - DeciVal = CDec(DeciVal) '<<< HAVE TO CONVERT TO DECIMAL - -End Sub - - -Sub DoubleDataType() - - 'Name: Double - 'Allocation: 8 Byte - 'Range: -1.79769313486231E308 to -4.94065645841247E-324 for negative numbers / 4.94065645841247E-324 to 1.79769313486232E308 for positive numbers - - Dim DoubleVal As Double - DoubleVal = 5.5 - - 'Using Character Type Method - DoubleVal# = -5.5 - -End Sub - -Sub IntegerDataType() - - 'Name: Integer - 'Allocation: 2 Byte - 'Range: -32,768 to 32,767 - - Dim IntVal As Integer - IntVal = 100 - - 'Using Character Type Method - IntVal% = -100 - -End Sub - -Sub LongDataType() - - 'Name: Long - 'Allocation: 4 Byte - 'Range: -2,147,483,648 and 2,147,483,647 - - Dim LongVal As Long - LongVal = 2000000 - - 'Using Character Type Method - LongVal& = -20000000 - -End Sub - -Sub LongLongDataType() - - 'Name: LongLong <<< ONLY VALID ON 64-BIT PLATFORMS - 'Allocation: 8 Byte - 'Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 - - Dim LngLngVal As LongLong - LngLngVal = -10000000000# - LngLngVal = 10000000000# - -End Sub - -Sub LongPtrDataType() - - 'Name: LongPtr <<< CHANGES DEPENDING ON THE PLATFORM - 'Allocation: 8 Byte - 'Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 - - Dim LngPtrVal As LongPtr - LngPtrVal = 1000000 '<<< 32 Bit Version Platform it becomes Long Data Type - LngPtrVal = 1000000 '<<< 64 Bit Version Platform it becomes LongLong Data Type - -End Sub - - -Sub ObjectDataType() - - 'Name: Object - 'Allocation: 4 Byte - 'Range: N/A - - Dim Rng As Object - Set Rng = Range("A1:A4") - -End Sub - - -Sub SingleDataType() - - 'Name: Single - 'Allocation: 4 Byte - 'Range: -3.402823E38 to -1.401298E-45 / 1.401298E-45 to 3.402823E38 - - Dim SingVal As Single - SingVal = -1.4 - - 'Using Character Type Method - SingVal! = 1.4 - -End Sub - - -Sub StringDataType() - - 'Name: String Variable / String Fixed - 'Allocation: 10 Byte + length of string / Length of String - 'Range: 0 to approximately 2 billion characters / 1 to approximately 65,400 - - Dim StrVal As String - StrVal = "Hello" - - 'Using Character Type Method - StrVal$ = "10" - -End Sub - - -Sub UserDefinedDataType() - - 'Name: User-Defined Types - 'Allocation: Varies - 'Range: Varies - - Type aType - Field1 As String - Field2 As Integer - Field3 As Boolean - End Type - - '("Hello", 10, True) - -End Sub - +Attribute VB_Name = "DataTypes" +Sub DataTypes() + + 'Name: Variant + 'Allocation: 16 to 22 bytes + 'Range: N/A + + 'Declare Variables with Variant Data Type + Dim EmptyValue As Variant + Dim ErrorValue As Variant + Dim NothingValue As Variant + Dim NullValue As Variant + + 'This means that no value has been assigned to the variable. + EmptyValue = Empty + + 'Error help us for identifying errors in our procedure. + ErrorValue = Error + + 'Nothing is the uninitialized state of an object variable. + Set NothingValue = Nothing + + 'This indicates that the variable is absent of data. + NullValue = Null + +End Sub + +Sub ByteDataType() + + 'Name: Byte + 'Allocation: 1 Bytes + 'Range: 0 to 255 + + Dim ByteValue As Byte + ByteValue = 100 + +End Sub + +Sub BooleanDataType() + + 'Name: Boolean + 'Allocation: 2 Bytes + 'Range: True or False + + Dim BooleanValue As Boolean + BooleanValue = True + BooleanValue = False + +End Sub + + +Sub CurrencyDataType() + + 'Name: Currency + 'Allocation: 8 Bytes + 'Range: -922,337,203,685,477.5808 and 922,337,203,685,477.5807 + + Dim CurrencyValue As Currency + CurrencyValue = 200000000 + + 'Using Character Type Method + CurrencyValue2@ = 200000000 + +End Sub + +Sub DateDataType() + + 'Name: Date + 'Allocation: 8 Bytes + 'Range Dates: Dates between January 1, 100 and December 31, 9999 + 'Range Times: Times between midnight (00:00:00) and 23:59:59 + + Dim DateValue As Date + DateValueSerial = 43435 '<<< This is 12/1/2018 + DateValueLiteral = #12/1/2018# + + TimeValueSerial = 0.54 '<<< This is 1:00:00PM + TimeValueLiteral = #1:00:00 PM# + + DateTimeValueSerial = 43435.54 '<<< This is 12/1/2018 1:00:00 PM + DateTimeValueLiteral = #12/1/2018 1:00:00 PM# + + DateValueSerialNeg = -1 '<<< This is 12/30/1899 + +End Sub + +Sub DecimalDataType() + + 'Name: Decimal + 'Allocation: 14 Byte + 'Range: +/-79,228,162,514,264,337,593,543,950,335 with no decial point / +/-7.9228162514264337593543950335 with 28 places to the right of the decimal + + Dim DeciVal As Variant + DeciVal = 1.15 + DeciVal = CDec(DeciVal) '<<< HAVE TO CONVERT TO DECIMAL + +End Sub + + +Sub DoubleDataType() + + 'Name: Double + 'Allocation: 8 Byte + 'Range: -1.79769313486231E308 to -4.94065645841247E-324 for negative numbers / 4.94065645841247E-324 to 1.79769313486232E308 for positive numbers + + Dim DoubleVal As Double + DoubleVal = 5.5 + + 'Using Character Type Method + DoubleVal# = -5.5 + +End Sub + +Sub IntegerDataType() + + 'Name: Integer + 'Allocation: 2 Byte + 'Range: -32,768 to 32,767 + + Dim IntVal As Integer + IntVal = 100 + + 'Using Character Type Method + IntVal% = -100 + +End Sub + +Sub LongDataType() + + 'Name: Long + 'Allocation: 4 Byte + 'Range: -2,147,483,648 and 2,147,483,647 + + Dim LongVal As Long + LongVal = 2000000 + + 'Using Character Type Method + LongVal& = -20000000 + +End Sub + +Sub LongLongDataType() + + 'Name: LongLong <<< ONLY VALID ON 64-BIT PLATFORMS + 'Allocation: 8 Byte + 'Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 + + Dim LngLngVal As LongLong + LngLngVal = -10000000000# + LngLngVal = 10000000000# + +End Sub + +Sub LongPtrDataType() + + 'Name: LongPtr <<< CHANGES DEPENDING ON THE PLATFORM + 'Allocation: 8 Byte + 'Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 + + Dim LngPtrVal As LongPtr + LngPtrVal = 1000000 '<<< 32 Bit Version Platform it becomes Long Data Type + LngPtrVal = 1000000 '<<< 64 Bit Version Platform it becomes LongLong Data Type + +End Sub + + +Sub ObjectDataType() + + 'Name: Object + 'Allocation: 4 Byte + 'Range: N/A + + Dim Rng As Object + Set Rng = Range("A1:A4") + +End Sub + + +Sub SingleDataType() + + 'Name: Single + 'Allocation: 4 Byte + 'Range: -3.402823E38 to -1.401298E-45 / 1.401298E-45 to 3.402823E38 + + Dim SingVal As Single + SingVal = -1.4 + + 'Using Character Type Method + SingVal! = 1.4 + +End Sub + + +Sub StringDataType() + + 'Name: String Variable / String Fixed + 'Allocation: 10 Byte + length of string / Length of String + 'Range: 0 to approximately 2 billion characters / 1 to approximately 65,400 + + Dim StrVal As String + StrVal = "Hello" + + 'Using Character Type Method + StrVal$ = "10" + +End Sub + + +Sub UserDefinedDataType() + + 'Name: User-Defined Types + 'Allocation: Varies + 'Range: Varies + + Type aType + Field1 As String + Field2 As Integer + Field3 As Boolean + End Type + + '("Hello", 10, True) + +End Sub + diff --git a/vba/excel-vba/core-concepts/Working With Arrays.bas b/vba/vba-core/Data Types - Arrays.bas similarity index 95% rename from vba/excel-vba/core-concepts/Working With Arrays.bas rename to vba/vba-core/Data Types - Arrays.bas index e52fb12..3cbeac4 100644 --- a/vba/excel-vba/core-concepts/Working With Arrays.bas +++ b/vba/vba-core/Data Types - Arrays.bas @@ -1,94 +1,94 @@ -Attribute VB_Name = "Arrays" -Sub DeclaringArrays() - -'Declare Array with range 0,1,2,3 -Dim MyArray(0 To 3) As Variant - -'Declare Array with range 0,1,2,3 -Dim MyArray(3) As Variant - -'Declare Array with range 1,2,3 -Dim MyArray(1 To 3) As Variant - -'Declare Array with range 2,3,4 -Dim MyArray(2 To 4) As Variant - -'DYNAMIC ARRAYS - -'Declare Array with Dynamic Range -Dim MyArray() As Variant - -'Resize Array with range 0,1,2,3,4 -ReDim MyArray(0 To 4) - -'ASSIGN VALUES TO AN ARRAY - -MyArray(0) = 100 -MyArray(1) = 200 -MyArray(2) = 300 -MyArray(3) = 400 -MyArray(4) = 500 - -MyArray(5) = 600 '<<< Will Return an error because there is not 5th element. - -'LOOP THROUGH ARRAYS - -'Using For Loop -Dim i As Long -For i = LBound(MyArray) To UBound(MyArray) - Debug.Print MyArray(i) -Next - -'Using For Each Loop -Dim Elem As Variant -For Each Elem In MyArray - Debug.Print Elem -Next - -'USE ERASE - -'Declare Static Array -Dim MyArray(0 To 3) As Long -Erase MyArray '<<< All Values will be set to 0. - -'Declare Dynamic Array -Dim MyArray() As Long -ReDim MyArray(0 To 3) -Erase MyArray '<<< Array is erased from memory. - -'USE REDIM - -Dim MyArray() As Variant -MyArray(0) = "MyFirstElement" - -'Old Array with "MyFirstElement" is now deleted. -ReDim MyArray(0 To 4) - - -Dim MyArray() As Variant -MyArray(0) = "MyFirstElement" - -'Old Array with "MyFirstElement" is now Resized With Original Content Kept in Place. -ReDim Preserve MyArray(0 To 4) - -'USING MULTIDIMENSIONAL ARRAYS - -'Declare two dimensional array -Dim MultiDimArray(0 To 3, 0 To 3) As Integer -Dim i, j As Integer - -'Assign values to array -For i = LBound(MultiDimArray, 1) To UBound(MultiDimArray, 1) - For j = LBound(MultiDimArray, 2) To UBound(MultiDimArray, 2) - MultiDimArray(i, j) = i + j - Next j -Next i - -'Print values from array. -For i = LBound(MultiDimArray, 1) To UBound(MultiDimArray, 1) - For j = LBound(MultiDimArray, 2) To UBound(MultiDimArray, 2) - Debug.Print MultiDimArray(i, j) - Next j -Next i - -End Sub +Attribute VB_Name = "Arrays" +Sub DeclaringArrays() + +'Declare Array with range 0,1,2,3 +Dim MyArray(0 To 3) As Variant + +'Declare Array with range 0,1,2,3 +Dim MyArray(3) As Variant + +'Declare Array with range 1,2,3 +Dim MyArray(1 To 3) As Variant + +'Declare Array with range 2,3,4 +Dim MyArray(2 To 4) As Variant + +'DYNAMIC ARRAYS + +'Declare Array with Dynamic Range +Dim MyArray() As Variant + +'Resize Array with range 0,1,2,3,4 +ReDim MyArray(0 To 4) + +'ASSIGN VALUES TO AN ARRAY + +MyArray(0) = 100 +MyArray(1) = 200 +MyArray(2) = 300 +MyArray(3) = 400 +MyArray(4) = 500 + +MyArray(5) = 600 '<<< Will Return an error because there is not 5th element. + +'LOOP THROUGH ARRAYS + +'Using For Loop +Dim i As Long +For i = LBound(MyArray) To UBound(MyArray) + Debug.Print MyArray(i) +Next + +'Using For Each Loop +Dim Elem As Variant +For Each Elem In MyArray + Debug.Print Elem +Next + +'USE ERASE + +'Declare Static Array +Dim MyArray(0 To 3) As Long +Erase MyArray '<<< All Values will be set to 0. + +'Declare Dynamic Array +Dim MyArray() As Long +ReDim MyArray(0 To 3) +Erase MyArray '<<< Array is erased from memory. + +'USE REDIM + +Dim MyArray() As Variant +MyArray(0) = "MyFirstElement" + +'Old Array with "MyFirstElement" is now deleted. +ReDim MyArray(0 To 4) + + +Dim MyArray() As Variant +MyArray(0) = "MyFirstElement" + +'Old Array with "MyFirstElement" is now Resized With Original Content Kept in Place. +ReDim Preserve MyArray(0 To 4) + +'USING MULTIDIMENSIONAL ARRAYS + +'Declare two dimensional array +Dim MultiDimArray(0 To 3, 0 To 3) As Integer +Dim i, j As Integer + +'Assign values to array +For i = LBound(MultiDimArray, 1) To UBound(MultiDimArray, 1) + For j = LBound(MultiDimArray, 2) To UBound(MultiDimArray, 2) + MultiDimArray(i, j) = i + j + Next j +Next i + +'Print values from array. +For i = LBound(MultiDimArray, 1) To UBound(MultiDimArray, 1) + For j = LBound(MultiDimArray, 2) To UBound(MultiDimArray, 2) + Debug.Print MultiDimArray(i, j) + Next j +Next i + +End Sub diff --git a/vba/excel-vba/core-concepts/Late And Early Binding.bas b/vba/vba-core/Data Types - Late Vs Early Binding.bas similarity index 96% rename from vba/excel-vba/core-concepts/Late And Early Binding.bas rename to vba/vba-core/Data Types - Late Vs Early Binding.bas index dd908a8..97d8ac9 100644 --- a/vba/excel-vba/core-concepts/Late And Early Binding.bas +++ b/vba/vba-core/Data Types - Late Vs Early Binding.bas @@ -1,66 +1,66 @@ -Sub EarlyBinding() - - 'Early Binding has several advantages. - 'We can use intellisense to help write our code, this is because the Object model is known. - 'The developer can also compile the code to assure there are no syntax errors. - 'Early binding runs a little faster than late binding. - - 'Here we are using early binding - We define the object types early on in the code. - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim ExcRng As Range - - 'Create a new instance of PowerPoint - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create a new Presentation - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new Slide - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutblank) - - 'Set a reference to the range - Set ExcRng = Range("A1:C5") - - 'Copy Range - ExcRng.Copy - - 'Create another slide - Set PPTSlide = PPTPres.Slides.Add(2, ppLayoutTitleOnly) - PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue - -End Sub - -Sub LateBinding() - - 'Here we are using late binding - We simply define the data type as general objects. - Dim PPTApp As Object - Dim PPTPres As Object - Dim PPTSlide As Object - Dim ExcRng As Object - - 'Create a new instance of PowerPoint - Set PPTApp = CreateObject("PowerPoint.Application") - PPTApp.Visible = True - - 'Create a new Presentation - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new Slide - Set PPTSlide = PPTPres.Slides.Add(1, 1) - - 'Set a reference to the range - Set ExcRng = Range("A1:C5") - - 'Copy Range - ExcRng.Copy - - 'Create another slide - Set PPTSlide = PPTPres.Slides.Add(2, 11) - - 'Paste the range in the slide - PPTSlide.Shapes.PasteSpecial DataType:=10 - -End Sub +Sub EarlyBinding() + + 'Early Binding has several advantages. + 'We can use intellisense to help write our code, this is because the Object model is known. + 'The developer can also compile the code to assure there are no syntax errors. + 'Early binding runs a little faster than late binding. + + 'Here we are using early binding - We define the object types early on in the code. + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim ExcRng As Range + + 'Create a new instance of PowerPoint + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create a new Presentation + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new Slide + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutblank) + + 'Set a reference to the range + Set ExcRng = Range("A1:C5") + + 'Copy Range + ExcRng.Copy + + 'Create another slide + Set PPTSlide = PPTPres.Slides.Add(2, ppLayoutTitleOnly) + PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue + +End Sub + +Sub LateBinding() + + 'Here we are using late binding - We simply define the data type as general objects. + Dim PPTApp As Object + Dim PPTPres As Object + Dim PPTSlide As Object + Dim ExcRng As Object + + 'Create a new instance of PowerPoint + Set PPTApp = CreateObject("PowerPoint.Application") + PPTApp.Visible = True + + 'Create a new Presentation + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new Slide + Set PPTSlide = PPTPres.Slides.Add(1, 1) + + 'Set a reference to the range + Set ExcRng = Range("A1:C5") + + 'Copy Range + ExcRng.Copy + + 'Create another slide + Set PPTSlide = PPTPres.Slides.Add(2, 11) + + 'Paste the range in the slide + PPTSlide.Shapes.PasteSpecial DataType:=10 + +End Sub diff --git a/vba/excel-vba/core-concepts/For Each Loop.bas b/vba/vba-core/Loops - For Each.bas similarity index 95% rename from vba/excel-vba/core-concepts/For Each Loop.bas rename to vba/vba-core/Loops - For Each.bas index b555ac1..c8b9606 100644 --- a/vba/excel-vba/core-concepts/For Each Loop.bas +++ b/vba/vba-core/Loops - For Each.bas @@ -1,78 +1,78 @@ -'For Each element In Group -' [statement 1] -' [statement 2] -' .... -' [statement n] -' [Exit For] -' [statement 11] -' [statement 22] -'Next - -Sub ForEachLoop() - - Dim WrkSht As Worksheet - - 'Loop through each worksheet (element) in the worksheet collection (group) - For Each WrkSht In ActiveWorkbook.Worksheets - Debug.Print WrkSht.Name - Next WrkSht - -End Sub - -Sub ForEachLoopExit() - - Dim WrkSht As Worksheet - - 'Loop through each worksheet (element) in the worksheet collection (group) - For Each WrkSht In ActiveWorkbook.Worksheets - - Debug.Print WrkSht.Name - - 'If you found the sheet then exit the for loop - If WrkSht.Name = "MySheet" Then - Exit For - End If - - Next WrkSht - -End Sub - -Sub ForEachLoopSimple() - - Dim WrkSht As Worksheet - - 'Loop through each worksheet (element) in the worksheet collection (group) - For Each WrkSht In ActiveWorkbook.Worksheets - - Debug.Print WrkSht.Name - - 'If you found the sheet then exit the for loop - If WrkSht.Name = "MySheet" Then - Exit For - End If - - Next - -End Sub - -Sub NestedForEachLoop() - - Dim WrkSht As Worksheet - Dim Rng As Range - Dim Cel As Range - - 'Loop through each worksheet (element) in th worksheet collection (group) - For Each WrkSht In ThisWorkbook.Worksheets - - 'Set a reference to a range. - Set Rng = WrkSht.Range("A1:B2") - - 'Loop through the cells in that range. - For Each Cel In Rng - - Cel.Value = 100 - - Next Cel - Next WrkSht - -End Sub +'For Each element In Group +' [statement 1] +' [statement 2] +' .... +' [statement n] +' [Exit For] +' [statement 11] +' [statement 22] +'Next + +Sub ForEachLoop() + + Dim WrkSht As Worksheet + + 'Loop through each worksheet (element) in the worksheet collection (group) + For Each WrkSht In ActiveWorkbook.Worksheets + Debug.Print WrkSht.Name + Next WrkSht + +End Sub + +Sub ForEachLoopExit() + + Dim WrkSht As Worksheet + + 'Loop through each worksheet (element) in the worksheet collection (group) + For Each WrkSht In ActiveWorkbook.Worksheets + + Debug.Print WrkSht.Name + + 'If you found the sheet then exit the for loop + If WrkSht.Name = "MySheet" Then + Exit For + End If + + Next WrkSht + +End Sub + +Sub ForEachLoopSimple() + + Dim WrkSht As Worksheet + + 'Loop through each worksheet (element) in the worksheet collection (group) + For Each WrkSht In ActiveWorkbook.Worksheets + + Debug.Print WrkSht.Name + + 'If you found the sheet then exit the for loop + If WrkSht.Name = "MySheet" Then + Exit For + End If + + Next + +End Sub + +Sub NestedForEachLoop() + + Dim WrkSht As Worksheet + Dim Rng As Range + Dim Cel As Range + + 'Loop through each worksheet (element) in th worksheet collection (group) + For Each WrkSht In ThisWorkbook.Worksheets + + 'Set a reference to a range. + Set Rng = WrkSht.Range("A1:B2") + + 'Loop through the cells in that range. + For Each Cel In Rng + + Cel.Value = 100 + + Next Cel + Next WrkSht + +End Sub diff --git a/vba/excel-vba/core-concepts/For Loops.bas b/vba/vba-core/Loops - For.bas similarity index 93% rename from vba/excel-vba/core-concepts/For Loops.bas rename to vba/vba-core/Loops - For.bas index c386b2d..d891187 100644 --- a/vba/excel-vba/core-concepts/For Loops.bas +++ b/vba/vba-core/Loops - For.bas @@ -1,80 +1,80 @@ -'BASIC SYNTAX -'For counter = start To end [Step increment] -' {...statements...} -'Next [counter] - - -'Parameters or Arguments - -'counter -'The loop counter variable. - -'Start -'The starting value for counter. - -'End -'The ending value for counter. - -'increment -'Optional. The value that counter is incremented each pass through the loop. -'It can be a positive or negative number. -'If not specified, it will default to an increment of 1 so that each pass through the loop increases counter by 1. - -'statements -'The statements of code to execute each pass through the loop. - -Sub ForLoops() - -'The basic for loop -For i = 1 To 10 - Cells(i, 1).Value = i -Next i - -End Sub - -Sub ForLoopsStep() - -'The basic for loop -For i = 1 To 10 Step 2 - Cells(i, 2).Value = i -Next i - -End Sub - -Sub ForLoopsReverse() - -'For loop going in reverse order. -For i = 10 To 1 Step -1 - Cells(i, 3).Value = i -Next i - -End Sub - -Sub NestedLoops() - -'Outer Loop -For i = 1 To 3 - 'Inner Loop - For j = 12 To 16 - Cells(j, i).Value = 100 - Next j -Next i - -End Sub - - -Sub ExitForLoop() - -For i = 1 To 20 - - ' Display the index. - Debug.Print i - - ' If index is 10, exit the loop. - If i = 10 Then - Exit For - End If - -Next i - -End Sub +'BASIC SYNTAX +'For counter = start To end [Step increment] +' {...statements...} +'Next [counter] + + +'Parameters or Arguments + +'counter +'The loop counter variable. + +'Start +'The starting value for counter. + +'End +'The ending value for counter. + +'increment +'Optional. The value that counter is incremented each pass through the loop. +'It can be a positive or negative number. +'If not specified, it will default to an increment of 1 so that each pass through the loop increases counter by 1. + +'statements +'The statements of code to execute each pass through the loop. + +Sub ForLoops() + +'The basic for loop +For i = 1 To 10 + Cells(i, 1).Value = i +Next i + +End Sub + +Sub ForLoopsStep() + +'The basic for loop +For i = 1 To 10 Step 2 + Cells(i, 2).Value = i +Next i + +End Sub + +Sub ForLoopsReverse() + +'For loop going in reverse order. +For i = 10 To 1 Step -1 + Cells(i, 3).Value = i +Next i + +End Sub + +Sub NestedLoops() + +'Outer Loop +For i = 1 To 3 + 'Inner Loop + For j = 12 To 16 + Cells(j, i).Value = 100 + Next j +Next i + +End Sub + + +Sub ExitForLoop() + +For i = 1 To 20 + + ' Display the index. + Debug.Print i + + ' If index is 10, exit the loop. + If i = 10 Then + Exit For + End If + +Next i + +End Sub diff --git a/vba/excel-vba/core-concepts/operators/Arithmetic Operators.bas b/vba/vba-core/operators/Operators - Arithmetic.bas similarity index 95% rename from vba/excel-vba/core-concepts/operators/Arithmetic Operators.bas rename to vba/vba-core/operators/Operators - Arithmetic.bas index 572f088..d974066 100644 --- a/vba/excel-vba/core-concepts/operators/Arithmetic Operators.bas +++ b/vba/vba-core/operators/Operators - Arithmetic.bas @@ -1,26 +1,26 @@ -Sub Operators() - - Dim IntOne As Integer - - 'Adding Two Numbers - IntOne = 5 + 5 - - 'Subtracting Two Numbers - IntOne = 5 - 5 - - 'Dividing Two Numbers - IntOne = 5 / 5 - - 'Multiplying Two Numbers - IntOne = 5 * 5 - - 'The Power Operator - IntOne = 2 ^ 2 - - 'Integer Division Operator - IntOne = 7 \ 4 'Divides two numbers and returns the integer in this case 1 - - 'Modulus - IntOne = 8 Mod 3 'Divides two numbers and returns the remainder in this case 2. - -End Sub +Sub Operators() + + Dim IntOne As Integer + + 'Adding Two Numbers + IntOne = 5 + 5 + + 'Subtracting Two Numbers + IntOne = 5 - 5 + + 'Dividing Two Numbers + IntOne = 5 / 5 + + 'Multiplying Two Numbers + IntOne = 5 * 5 + + 'The Power Operator + IntOne = 2 ^ 2 + + 'Integer Division Operator + IntOne = 7 \ 4 'Divides two numbers and returns the integer in this case 1 + + 'Modulus + IntOne = 8 Mod 3 'Divides two numbers and returns the remainder in this case 2. + +End Sub diff --git a/vba/excel-vba/core-concepts/operators/Comparison Operators.bas b/vba/vba-core/operators/Operators - Comparison.bas similarity index 96% rename from vba/excel-vba/core-concepts/operators/Comparison Operators.bas rename to vba/vba-core/operators/Operators - Comparison.bas index b6bdfa6..53b2ebb 100644 --- a/vba/excel-vba/core-concepts/operators/Comparison Operators.bas +++ b/vba/vba-core/operators/Operators - Comparison.bas @@ -1,44 +1,44 @@ -Sub ComparisonOperators() - -'Comparison operators compare two expressions and return a Boolean value that represents the relationship of their values. _ -'There are operators for comparing numeric values, operators for comparing strings, and operators for comparing objects. - -'Equality Operator - MsgBox 23 = 33 ' Returns False - MsgBox 10 = 10 ' Returns True - -'Inequality Operator - MsgBox 23 <> 33 ' Returns True - MsgBox 10 <> 10 ' Returns False - -'Less Than Operator - MsgBox 23 < 33 ' Returns True - MsgBox 10 < 10 ' Returns False - MsgBox 23 < 12 ' Returns False - -'Greater Than Operator - MsgBox 23 > 33 ' Returns False - MsgBox 10 > 10 ' Returns False - MsgBox 23 > 12 ' Returns True - -'Less Than Or Equal To Operator - MsgBox 23 <= 33 ' Returns True - MsgBox 10 <= 10 ' Returns True - MsgBox 23 <= 12 ' Returns False - -'Greater Than Or Equal To Operator - MsgBox 23 >= 33 ' Returns False - MsgBox 10 >= 10 ' Returns True - MsgBox 23 >= 12 ' Returns True - -End Sub - -Sub TypeProperty() - - Set Rng = Range("A1") - - If TypeOf Rng Is Range Then - MsgBox "You Have a Range" - End If - -End Sub +Sub ComparisonOperators() + +'Comparison operators compare two expressions and return a Boolean value that represents the relationship of their values. _ +'There are operators for comparing numeric values, operators for comparing strings, and operators for comparing objects. + +'Equality Operator + MsgBox 23 = 33 ' Returns False + MsgBox 10 = 10 ' Returns True + +'Inequality Operator + MsgBox 23 <> 33 ' Returns True + MsgBox 10 <> 10 ' Returns False + +'Less Than Operator + MsgBox 23 < 33 ' Returns True + MsgBox 10 < 10 ' Returns False + MsgBox 23 < 12 ' Returns False + +'Greater Than Operator + MsgBox 23 > 33 ' Returns False + MsgBox 10 > 10 ' Returns False + MsgBox 23 > 12 ' Returns True + +'Less Than Or Equal To Operator + MsgBox 23 <= 33 ' Returns True + MsgBox 10 <= 10 ' Returns True + MsgBox 23 <= 12 ' Returns False + +'Greater Than Or Equal To Operator + MsgBox 23 >= 33 ' Returns False + MsgBox 10 >= 10 ' Returns True + MsgBox 23 >= 12 ' Returns True + +End Sub + +Sub TypeProperty() + + Set Rng = Range("A1") + + If TypeOf Rng Is Range Then + MsgBox "You Have a Range" + End If + +End Sub diff --git a/vba/excel-vba/core-concepts/operators/Logical Operators.bas b/vba/vba-core/operators/Operators - Logical.bas similarity index 95% rename from vba/excel-vba/core-concepts/operators/Logical Operators.bas rename to vba/vba-core/operators/Operators - Logical.bas index 9fe14ab..9973db0 100644 --- a/vba/excel-vba/core-concepts/operators/Logical Operators.bas +++ b/vba/vba-core/operators/Operators - Logical.bas @@ -1,53 +1,53 @@ -Attribute VB_Name = "LogicalOperators" -Sub Logical_Operators() - - Dim a As Integer - Dim b As Integer - - a = 100 - b = 0 - - 'The AND operator - If a <> 0 And b <> 0 Then - MsgBox ("AND Operator Result is : True") - Else - MsgBox ("AND Operator Result is : False") - End If - - 'The OR operator - If a <> 0 Or b <> 0 Then - MsgBox ("OR Operator Result is : True") - Else - MsgBox ("OR Operator Result is : False") - End If - - 'The NOT operator - If Not (a <> 0 Or b <> 0) Then - MsgBox ("NOT Operator Result is : True") - Else - MsgBox ("NOT Operator Result is : False") - End If - - 'The XOR operator - If (a <> 0 Xor b <> 0) Then - MsgBox ("XOR Operator Result is : True") - Else - MsgBox ("XOR Operator Result is : False") - End If - - 'The EQV operator - If (a <> 0 Eqv a = 100) Then - MsgBox ("EQV Operator Result is : True") - Else - MsgBox ("EQV Operator Result is : False") - End If - - 'The IMP operator - 'If A is true, then B must be true - If (a <> 0 Imp b = 0) Then - MsgBox ("IMP Operator Result is : True") - Else - MsgBox ("IMP Operator Result is : False") - End If - -End Sub +Attribute VB_Name = "LogicalOperators" +Sub Logical_Operators() + + Dim a As Integer + Dim b As Integer + + a = 100 + b = 0 + + 'The AND operator + If a <> 0 And b <> 0 Then + MsgBox ("AND Operator Result is : True") + Else + MsgBox ("AND Operator Result is : False") + End If + + 'The OR operator + If a <> 0 Or b <> 0 Then + MsgBox ("OR Operator Result is : True") + Else + MsgBox ("OR Operator Result is : False") + End If + + 'The NOT operator + If Not (a <> 0 Or b <> 0) Then + MsgBox ("NOT Operator Result is : True") + Else + MsgBox ("NOT Operator Result is : False") + End If + + 'The XOR operator + If (a <> 0 Xor b <> 0) Then + MsgBox ("XOR Operator Result is : True") + Else + MsgBox ("XOR Operator Result is : False") + End If + + 'The EQV operator + If (a <> 0 Eqv a = 100) Then + MsgBox ("EQV Operator Result is : True") + Else + MsgBox ("EQV Operator Result is : False") + End If + + 'The IMP operator + 'If A is true, then B must be true + If (a <> 0 Imp b = 0) Then + MsgBox ("IMP Operator Result is : True") + Else + MsgBox ("IMP Operator Result is : False") + End If + +End Sub diff --git a/vba/excel-vba/core-concepts/operators/String Operators.bas b/vba/vba-core/operators/Operators - Strings.bas similarity index 96% rename from vba/excel-vba/core-concepts/operators/String Operators.bas rename to vba/vba-core/operators/Operators - Strings.bas index 98c0a1b..c49ab28 100644 --- a/vba/excel-vba/core-concepts/operators/String Operators.bas +++ b/vba/vba-core/operators/Operators - Strings.bas @@ -1,34 +1,34 @@ -Sub StringOperators() - - 'Comments are preceded by the "'" symbol - - Str1 = "Hi" - Str2 = "There" - - 'This is how we combine two strings using the "&" and the "+" symbols. - MsgBox Str1 + " " + Str2 - MsgBox Str1 & " " & Str2 - - 'Here is how write combine multiple lines into a single line using the "&" and "+" symbol. - MultiLineStr = "Hi There " + _ - "my name is " + _ - "Alex" - - MultiLineStr = "Hi There " & _ - "my name is " & _ - "Alex" - - MsgBox MultiLineStr - - 'Lets see if we can condense this for loop into a single line. - For i = 1 To 10 - - x = 1 + 1 - - Next i - - 'If we use the ":" symbol we can combine all the different parts into a single line. - For i = 1 To 10: x = 1 + 1: Next i - - -End Sub +Sub StringOperators() + + 'Comments are preceded by the "'" symbol + + Str1 = "Hi" + Str2 = "There" + + 'This is how we combine two strings using the "&" and the "+" symbols. + MsgBox Str1 + " " + Str2 + MsgBox Str1 & " " & Str2 + + 'Here is how write combine multiple lines into a single line using the "&" and "+" symbol. + MultiLineStr = "Hi There " + _ + "my name is " + _ + "Alex" + + MultiLineStr = "Hi There " & _ + "my name is " & _ + "Alex" + + MsgBox MultiLineStr + + 'Lets see if we can condense this for loop into a single line. + For i = 1 To 10 + + x = 1 + 1 + + Next i + + 'If we use the ":" symbol we can combine all the different parts into a single line. + For i = 1 To 10: x = 1 + 1: Next i + + +End Sub diff --git a/vba/excel-vba/core-concepts/variables/Declare Variables.bas b/vba/vba-core/variables/Variables - Declare.bas similarity index 95% rename from vba/excel-vba/core-concepts/variables/Declare Variables.bas rename to vba/vba-core/variables/Variables - Declare.bas index dc06091..661a157 100644 --- a/vba/excel-vba/core-concepts/variables/Declare Variables.bas +++ b/vba/vba-core/variables/Variables - Declare.bas @@ -1,16 +1,16 @@ -Attribute VB_Name = "VariablesDeclare" -Option Explicit - -Sub Declaring_Variables() - - 'The explicit way - Dim FirstName As String - FirstName = "Alex" - - 'The implicit way, but keep in mind it's now variant. - LastName = "Awesome" - - 'Using the let statement. - Let MiddleName = "Cool" - -End Sub +Attribute VB_Name = "VariablesDeclare" +Option Explicit + +Sub Declaring_Variables() + + 'The explicit way + Dim FirstName As String + FirstName = "Alex" + + 'The implicit way, but keep in mind it's now variant. + LastName = "Awesome" + + 'Using the let statement. + Let MiddleName = "Cool" + +End Sub diff --git a/vba/excel-vba/core-concepts/variables/Variables Run.bas b/vba/vba-core/variables/Variables - Run.bas similarity index 94% rename from vba/excel-vba/core-concepts/variables/Variables Run.bas rename to vba/vba-core/variables/Variables - Run.bas index 39e8823..727713b 100644 --- a/vba/excel-vba/core-concepts/variables/Variables Run.bas +++ b/vba/vba-core/variables/Variables - Run.bas @@ -1,18 +1,18 @@ -Attribute VB_Name = "VariablesRun" -Option Explicit - -'Call my public variable. -Sub CallPublicVariable() - - Call PrintPublicVariable - MsgBox PublicVariable - -End Sub - -'Call my private variable. -Sub CallPrivateVariable() - - Call PrintPrivateVariable - MsgBox PrivateVariable - -End Sub +Attribute VB_Name = "VariablesRun" +Option Explicit + +'Call my public variable. +Sub CallPublicVariable() + + Call PrintPublicVariable + MsgBox PublicVariable + +End Sub + +'Call my private variable. +Sub CallPrivateVariable() + + Call PrintPrivateVariable + MsgBox PrivateVariable + +End Sub diff --git a/vba/excel-vba/core-concepts/variables/Variables Static.bas b/vba/vba-core/variables/Variables - Static.bas similarity index 94% rename from vba/excel-vba/core-concepts/variables/Variables Static.bas rename to vba/vba-core/variables/Variables - Static.bas index f0dba22..9c3db9d 100644 --- a/vba/excel-vba/core-concepts/variables/Variables Static.bas +++ b/vba/vba-core/variables/Variables - Static.bas @@ -1,22 +1,22 @@ -Attribute VB_Name = "VariablesStatic" -Option Explicit - -Sub Static_Variables() - - Dim NumOne As Integer - Static NumTwo As Integer - - NumOne = NumOne + 1 - NumTwo = NumTwo + 1 - - MsgBox "Number One Value: " & NumOne - MsgBox "Number Two Value: " & NumTwo - -End Sub - -'Run to see static versus dim variable. -Sub Run_Static_Procedure() - - Call Static_Variables - -End Sub +Attribute VB_Name = "VariablesStatic" +Option Explicit + +Sub Static_Variables() + + Dim NumOne As Integer + Static NumTwo As Integer + + NumOne = NumOne + 1 + NumTwo = NumTwo + 1 + + MsgBox "Number One Value: " & NumOne + MsgBox "Number Two Value: " & NumTwo + +End Sub + +'Run to see static versus dim variable. +Sub Run_Static_Procedure() + + Call Static_Variables + +End Sub diff --git a/vba/excel-vba/core-concepts/variables/Variables.bas b/vba/vba-core/variables/Variables.bas similarity index 94% rename from vba/excel-vba/core-concepts/variables/Variables.bas rename to vba/vba-core/variables/Variables.bas index 8edcac8..e1cb91c 100644 --- a/vba/excel-vba/core-concepts/variables/Variables.bas +++ b/vba/vba-core/variables/Variables.bas @@ -1,26 +1,26 @@ -Attribute VB_Name = "Variables" -Option Explicit - -Public PublicVariable As Integer -Private PrivateVariable As Integer - -'Populate the public variable. -Sub PrintPublicVariable() - - PublicVariable = 1000 - -End Sub - -'Populate the private variable. -Sub PrintPrivateVariable() - - PrivateVariable = 2000 - -End Sub - -Sub CallPrivateVariable() - - Call PrintPrivateVariable - MsgBox PrivateVariable - -End Sub +Attribute VB_Name = "Variables" +Option Explicit + +Public PublicVariable As Integer +Private PrivateVariable As Integer + +'Populate the public variable. +Sub PrintPublicVariable() + + PublicVariable = 1000 + +End Sub + +'Populate the private variable. +Sub PrintPrivateVariable() + + PrivateVariable = 2000 + +End Sub + +Sub CallPrivateVariable() + + Call PrintPrivateVariable + MsgBox PrivateVariable + +End Sub diff --git a/vba/excel-vba/chart-objects/Charts Part 1.bas b/vba/vba-excel/chart-objects/Charts Part 1.bas similarity index 100% rename from vba/excel-vba/chart-objects/Charts Part 1.bas rename to vba/vba-excel/chart-objects/Charts Part 1.bas diff --git a/vba/excel-vba/chart-objects/Charts Part 2.bas b/vba/vba-excel/chart-objects/Charts Part 2.bas similarity index 100% rename from vba/excel-vba/chart-objects/Charts Part 2.bas rename to vba/vba-excel/chart-objects/Charts Part 2.bas diff --git a/vba/excel-vba/chart-objects/Chart Part 3.bas b/vba/vba-excel/chart-objects/Charts Part 3.bas similarity index 100% rename from vba/excel-vba/chart-objects/Chart Part 3.bas rename to vba/vba-excel/chart-objects/Charts Part 3.bas diff --git a/vba/excel-vba/connection-objects/connection-xls.vb b/vba/vba-excel/connection-objects/connection-xls.vb similarity index 100% rename from vba/excel-vba/connection-objects/connection-xls.vb rename to vba/vba-excel/connection-objects/connection-xls.vb diff --git a/vba/excel-vba/data-imports/Import Text File - Non Power Query.bas b/vba/vba-excel/data-imports/Import Text File - Non Power Query.bas similarity index 100% rename from vba/excel-vba/data-imports/Import Text File - Non Power Query.bas rename to vba/vba-excel/data-imports/Import Text File - Non Power Query.bas diff --git a/vba/excel-vba/core-concepts/Formatting Cells.bas b/vba/vba-excel/formatting/Formatting Cells.bas similarity index 97% rename from vba/excel-vba/core-concepts/Formatting Cells.bas rename to vba/vba-excel/formatting/Formatting Cells.bas index 63a163f..6814346 100644 --- a/vba/excel-vba/core-concepts/Formatting Cells.bas +++ b/vba/vba-excel/formatting/Formatting Cells.bas @@ -1,203 +1,203 @@ -Attribute VB_Name = "Module1" -Option Explicit - -Sub Formats() - -'Change the Number Format of a Cell -Range("A1").NumberFormat = "General" -Range("A1").NumberFormat = "$#,##0.00" -Range("A1").NumberFormat = "$#,##0.00_);[Red]($#,##0.00)" - -'Change the Horizontal alignment of a cell. -Range("A1").HorizontalAlignment = xlHAlignCenter - - 'Name Value Description - 'xlHAlignCenter -4108 Center. - 'xlHAlignCenterAcrossSelection 7 Center across selection. - 'xlHAlignDistributed -4117 Distribute. - 'xlHAlignFill 5 Fill. - 'xlHAlignGeneral 1 Align according to data type. - 'xlHAlignJustify -4130 Justify. - 'xlHAlignLeft -4131 Left. - 'xlHAlignRight -4152 Right. - -'Change the Vertical alignment of a cell. -Range("A1").VerticalAlignment = xlVAlignTop - - 'Name Value Description - 'xlVAlignBottom -4107 Bottom - 'xlVAlignCenter -4108 Center - 'xlVAlignDistributed -4117 Distributed - 'xlVAlignJustify -4130 Justify - 'xlVAlignTop -4160 Top - -'Wrape the text content of a cell. -Range("A1").WrapText = True - -'If set to true it will automatically reduce the size of the font in order to fit the content in the column width. -Rows(1).ShrinkToFit = True - -'Merge a Range of Cells -Range("A1:A4").MergeCells = True - -'Change the reading order of a Cell. -Range("A1").ReadingOrder = xlRTL - - 'Possible Values - 'xlRTL - 'xlLTR - 'xlContext - -'Change the orientation of the cell content. -Range("A1").Orientation = xlHorizontal - - 'Possible Values - 'xlDownward - 'xlHorizontal - 'xlUpward - 'xlVertical - - -'Change the font of a cell. -Range("A1:A5").Font.Name = "Calibri" - -'Change the font style of a cell. -Range("A1:A5").Font.FontStyle = "Italic" - - 'Possible Values - 'Regular - 'Bold - 'Italic - 'Bold Italic - -'Change the Font Size - Range 1 to 409 -Range("A1").Font.Size = 14 - -'Change the Underline Style of a Font. -Range("A1").Font.Underline = xlUnderlineStyleDouble - - 'Name Value Description - 'xlUnderlineStyleDouble -4119 Double thick underline. - 'xlUnderlineStyleDoubleAccounting 5 Two thin underlines placed close together. - 'xlUnderlineStyleNone -4142 No underlining. - 'xlUnderlineStyleSingle 2 Single underlining. - - -'Change the font color, using different methods. -Range("A1").Font.Color = vbBlack -Range("A1").Font.Color = 0 -Range("A1").Font.Color = RGB(0, 0, 0) - -'Add Font, Strikethrough, subscript, or superscript. -Range("A1").Font.Strikethrough = True -Range("A1").Font.Subscript = True -Range("A1").Font.Superscript = True - -'Add a Cell Border, and select a border style. -Range("A1").Borders(xlEdgeBottom).LineStyle = xlContinuous -Range("A1").Borders(xlEdgeBottom).LineStyle = xlNone - - 'Border Constant Value Description - 'xlDiagonalDown 5 (Border running from the upper left-hand corner to the lower right of each cell in the range). - 'xlDiagonalUp 6 (Border running from the lower left-hand corner to the upper right of each cell in the range). - 'xlEdgeBottom 9 (Border at the bottom of the range). - 'xlEdgeLeft 7 (Border at the left-hand edge of the range). - 'xlEdgeRight 10 (Border at the right-hand edge of the range). - 'xlEdgeTop 8 (Border at the top of the range). - 'xlInsideHorizontal 12 (Horizontal borders for all cells in the range except borders on the outside of the range). - 'xlInsideVertical 11 (Vertical borders for all the cells in the range except borders on the outside of the range). - - - 'Name Value Description - 'xlContinuous 1 Continuous line. - 'xlDash -4115 Dashed line. - 'xlDashDot 4 Alternating dashes and dots. - 'xlDashDotDot 5 Dash followed by two dots. - 'xlDot -4118 Dotted line. - 'xlDouble -4119 Double line. - 'xlLineStyleNone -4142 No line. - 'xlSlantDashDot 13 Slanted dashes. - - -'Change the border weight -Range("A1").Borders(xlEdgeBottom).Weight = xlThin - - 'Name Value Description - 'xlHairline 1 Hairline (thinnest border). - 'xlMedium -4138 Medium. - 'xlThick 4 Thick (widest border). - 'xlThin 2 Thin. - -'Change the Border Color. -Range("A1").Borders(xlEdgeBottom).Color = vbGreen -Range("A1").Borders(xlEdgeBottom).Color = RGB(255, 0, 0) - -'Change the Pattern of the cell interior. -Range("A1").Interior.Pattern = xlPatternCrissCross - -'xlPatternAutomatic (Excel controls the pattern.) -'xlPatternChecker (Checkerboard.) -'xlPatternCrissCross (Criss-cross lines.) -'xlPatternDown (Dark diagonal lines running from the upper left to the lower right.) -'xlPatternGray16 (16% gray.) -'xlPatternGray25 (25% gray.) -'xlPatternGray50 (50% gray.) -'xlPatternGray75 (75% gray.) -'xlPatternGray8 (8% gray.) -'xlPatternGrid (Grid.) -'xlPatternHorizontal (Dark horizontal lines.) -'xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.) -'xlPatternLightHorizontal (Light horizontal lines.) -'xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.) -'xlPatternLightVertical (Light vertical bars.) -'xlPatternNone (No pattern.) -'xlPatternSemiGray75 (75% dark moiré.) -'xlPatternSolid (Solid color.) -'xlPatternUp (Dark diagonal lines running from the lower left to the upper right.) - -'Change the interior color of the cell. -Range("A1").Interior.Color = RGB(255, 0, 0) - -'You can enter a number from -1 (darkest) to 1 (lightest) for the TintAndShade property. Zero (0) is neutral. -Range("A1").Interior.TintAndShade - -'Change the Cell interior to a theme color. -Range("A1").Interior.ThemeColor = xlThemeColorDark1 - - - -End Sub - - -Sub Test() - - 'Add Gradients - With Range("C1").Interior - .Pattern = xlPatternLinearGradient - .Gradient.Degree = 180 - - 'Adjust Color Stops - 'Clear Default Color Stops - .Gradient.ColorStops.Clear - - 'Add A Color Stop - With .Gradient.ColorStops.Add(0) - .Color = RGB(255, 255, 255) - End With - - 'Add Another Color Stop - With .Gradient.ColorStops.Add(1) - .Color = RGB(141, 180, 227) - End With - End With - - - - -End Sub - -Sub row() - -Rows(5).ShrinkToFit = True - -End Sub +Attribute VB_Name = "Module1" +Option Explicit + +Sub Formats() + +'Change the Number Format of a Cell +Range("A1").NumberFormat = "General" +Range("A1").NumberFormat = "$#,##0.00" +Range("A1").NumberFormat = "$#,##0.00_);[Red]($#,##0.00)" + +'Change the Horizontal alignment of a cell. +Range("A1").HorizontalAlignment = xlHAlignCenter + + 'Name Value Description + 'xlHAlignCenter -4108 Center. + 'xlHAlignCenterAcrossSelection 7 Center across selection. + 'xlHAlignDistributed -4117 Distribute. + 'xlHAlignFill 5 Fill. + 'xlHAlignGeneral 1 Align according to data type. + 'xlHAlignJustify -4130 Justify. + 'xlHAlignLeft -4131 Left. + 'xlHAlignRight -4152 Right. + +'Change the Vertical alignment of a cell. +Range("A1").VerticalAlignment = xlVAlignTop + + 'Name Value Description + 'xlVAlignBottom -4107 Bottom + 'xlVAlignCenter -4108 Center + 'xlVAlignDistributed -4117 Distributed + 'xlVAlignJustify -4130 Justify + 'xlVAlignTop -4160 Top + +'Wrape the text content of a cell. +Range("A1").WrapText = True + +'If set to true it will automatically reduce the size of the font in order to fit the content in the column width. +Rows(1).ShrinkToFit = True + +'Merge a Range of Cells +Range("A1:A4").MergeCells = True + +'Change the reading order of a Cell. +Range("A1").ReadingOrder = xlRTL + + 'Possible Values + 'xlRTL + 'xlLTR + 'xlContext + +'Change the orientation of the cell content. +Range("A1").Orientation = xlHorizontal + + 'Possible Values + 'xlDownward + 'xlHorizontal + 'xlUpward + 'xlVertical + + +'Change the font of a cell. +Range("A1:A5").Font.Name = "Calibri" + +'Change the font style of a cell. +Range("A1:A5").Font.FontStyle = "Italic" + + 'Possible Values + 'Regular + 'Bold + 'Italic + 'Bold Italic + +'Change the Font Size - Range 1 to 409 +Range("A1").Font.Size = 14 + +'Change the Underline Style of a Font. +Range("A1").Font.Underline = xlUnderlineStyleDouble + + 'Name Value Description + 'xlUnderlineStyleDouble -4119 Double thick underline. + 'xlUnderlineStyleDoubleAccounting 5 Two thin underlines placed close together. + 'xlUnderlineStyleNone -4142 No underlining. + 'xlUnderlineStyleSingle 2 Single underlining. + + +'Change the font color, using different methods. +Range("A1").Font.Color = vbBlack +Range("A1").Font.Color = 0 +Range("A1").Font.Color = RGB(0, 0, 0) + +'Add Font, Strikethrough, subscript, or superscript. +Range("A1").Font.Strikethrough = True +Range("A1").Font.Subscript = True +Range("A1").Font.Superscript = True + +'Add a Cell Border, and select a border style. +Range("A1").Borders(xlEdgeBottom).LineStyle = xlContinuous +Range("A1").Borders(xlEdgeBottom).LineStyle = xlNone + + 'Border Constant Value Description + 'xlDiagonalDown 5 (Border running from the upper left-hand corner to the lower right of each cell in the range). + 'xlDiagonalUp 6 (Border running from the lower left-hand corner to the upper right of each cell in the range). + 'xlEdgeBottom 9 (Border at the bottom of the range). + 'xlEdgeLeft 7 (Border at the left-hand edge of the range). + 'xlEdgeRight 10 (Border at the right-hand edge of the range). + 'xlEdgeTop 8 (Border at the top of the range). + 'xlInsideHorizontal 12 (Horizontal borders for all cells in the range except borders on the outside of the range). + 'xlInsideVertical 11 (Vertical borders for all the cells in the range except borders on the outside of the range). + + + 'Name Value Description + 'xlContinuous 1 Continuous line. + 'xlDash -4115 Dashed line. + 'xlDashDot 4 Alternating dashes and dots. + 'xlDashDotDot 5 Dash followed by two dots. + 'xlDot -4118 Dotted line. + 'xlDouble -4119 Double line. + 'xlLineStyleNone -4142 No line. + 'xlSlantDashDot 13 Slanted dashes. + + +'Change the border weight +Range("A1").Borders(xlEdgeBottom).Weight = xlThin + + 'Name Value Description + 'xlHairline 1 Hairline (thinnest border). + 'xlMedium -4138 Medium. + 'xlThick 4 Thick (widest border). + 'xlThin 2 Thin. + +'Change the Border Color. +Range("A1").Borders(xlEdgeBottom).Color = vbGreen +Range("A1").Borders(xlEdgeBottom).Color = RGB(255, 0, 0) + +'Change the Pattern of the cell interior. +Range("A1").Interior.Pattern = xlPatternCrissCross + +'xlPatternAutomatic (Excel controls the pattern.) +'xlPatternChecker (Checkerboard.) +'xlPatternCrissCross (Criss-cross lines.) +'xlPatternDown (Dark diagonal lines running from the upper left to the lower right.) +'xlPatternGray16 (16% gray.) +'xlPatternGray25 (25% gray.) +'xlPatternGray50 (50% gray.) +'xlPatternGray75 (75% gray.) +'xlPatternGray8 (8% gray.) +'xlPatternGrid (Grid.) +'xlPatternHorizontal (Dark horizontal lines.) +'xlPatternLightDown (Light diagonal lines running from the upper left to the lower right.) +'xlPatternLightHorizontal (Light horizontal lines.) +'xlPatternLightUp (Light diagonal lines running from the lower left to the upper right.) +'xlPatternLightVertical (Light vertical bars.) +'xlPatternNone (No pattern.) +'xlPatternSemiGray75 (75% dark moiré.) +'xlPatternSolid (Solid color.) +'xlPatternUp (Dark diagonal lines running from the lower left to the upper right.) + +'Change the interior color of the cell. +Range("A1").Interior.Color = RGB(255, 0, 0) + +'You can enter a number from -1 (darkest) to 1 (lightest) for the TintAndShade property. Zero (0) is neutral. +Range("A1").Interior.TintAndShade + +'Change the Cell interior to a theme color. +Range("A1").Interior.ThemeColor = xlThemeColorDark1 + + + +End Sub + + +Sub Test() + + 'Add Gradients + With Range("C1").Interior + .Pattern = xlPatternLinearGradient + .Gradient.Degree = 180 + + 'Adjust Color Stops + 'Clear Default Color Stops + .Gradient.ColorStops.Clear + + 'Add A Color Stop + With .Gradient.ColorStops.Add(0) + .Color = RGB(255, 255, 255) + End With + + 'Add Another Color Stop + With .Gradient.ColorStops.Add(1) + .Color = RGB(141, 180, 227) + End With + End With + + + + +End Sub + +Sub row() + +Rows(5).ShrinkToFit = True + +End Sub diff --git a/vba/excel-vba/list-objects/Working With List Objects.bas b/vba/vba-excel/list-objects/Working With List Objects.bas similarity index 97% rename from vba/excel-vba/list-objects/Working With List Objects.bas rename to vba/vba-excel/list-objects/Working With List Objects.bas index 2ecea93..b7f8b43 100644 --- a/vba/excel-vba/list-objects/Working With List Objects.bas +++ b/vba/vba-excel/list-objects/Working With List Objects.bas @@ -1,111 +1,111 @@ -Sub CreateListObject() - - Dim ListObj As ListObject - Set ListObj = ActiveSheet.ListObjects.Add(SourceType:=xlSrcRange, _ - Source:=Range("$A$1:$C$5"), _ - XlListObjectHasHeaders:=xlNo, _ - Destination:=Range("$I$1"), _ - TableStyleName:="TableStyleLight1") - - 'PARMETER ONE: - 'SourceType:= xlSrcExternal, (External Data Connection) _ - xlSrcModel (PowerPivot Model), _ - xlSrcQuery (Query), _ - xlSrcRange (Range), _ - xlSrcXml (XML) - - 'PARAMTER TWO: - 'Source:= When SourceType equal xlSrcRange we need to pass through a range object. _ - If Omitted, then the source will default to the range returned by the list range _ - detection code. When SourceType equals xlSrcExternal an array of string values must be _ - passed through with the following three elements: _ - 0 - URL to SharePoint Site _ - 1 - ListName _ - 2 - View GUID - - 'PARAMETER THREE: - 'LinkSource:= Indicates whether an external data source is to be linked to the ListObject object. _ - If SourceType is xlSrcExternal, default is True. Invalid if SourceType is xlSrcRange , _ - and will return an error if not omitted. - - 'PARAMETER FOUR: - 'XlListObjectHasHeaders:= An xlYesNoGuess constant that indicates whether the data being imported has column labels. _ - If the Source does not contain headers, Excel will automatically generate headers. _ - Value Default: xlGuess. _ - Value Yes: xlYes. _ - Value No: xlNo. - - - 'PARAMETER FIVE: - 'Destination:= A Range object specifying a single-cell reference as the destination for the top-left corner of the new list object. _ - If the Range object refers to more than one cell, an error is generated. The Destination argument must be specified when SourceType is set to xlSrcExternal. _ - The Destination argument is ignored if SourceType is set to xlSrcRange. The destination range must be on the worksheet that _ - contains the ListObjects collection specified by expression. New columns will be inserted at the Destination to fit the new list. _ - Therefore, existing data will not be overwritten. - - 'PARAMETER SIX: - 'TableStyleName:= This is the name of a table style that we can apply to the table, in this example we used TableStyleLight1. - - -End Sub - -Sub CreateTableFromSharePointList() - - 'Declare Variables - Dim Server As String - Dim ListName As String - Dim ViewName As String - Dim ListObj As ListObject - - 'Get Connection String Paramaters - Server = "https://petco.sharepoint.com/sites/AnalyticsCommunity/_vti_bin" '<<< THIS IS YOUR SHAREPOINT SITE REPLACE WIT THE PROPER URL & MAKE SURE Vti_bin IS AT THE END. - ListName = "{6DC036F2-05F3-4EB9-A732-43E1C6827682}" '<<< This is the list name - ViewName = "{5D8F3E3B-2425-4CCB-953C-22E82242EC05}" '<<< This is the view name - - - 'TO GET THE LIST NAME/ID - 'Go To the List in SharePoin, click Settings & then right click "Audience Target Settings" - - 'Click Copy link address & Paste it in VBA. - 'https://petco.sharepoint.com/sites/AnalyticsCommunity/_layouts/ListEnableTargeting.aspx?List={6dc036f2-05f3-4eb9-a732-43e1c6827682} - - 'Delete Everything Before List & this is the List ID/Name: - 'List={6dc036f2-05f3-4eb9-a732-43e1c6827682} - - - 'TO GET THE VIEW ID - 'Go to the list in SharePoint, then the list section at the top of the ribbon, click modify view, & copy the URL on the new page. - 'https://petco.sharepoint.com/sites/AnalyticsCommunity/_layouts/15/ViewEdit.aspx?List=6dc036f2-05f3-4eb9-a732-43e1c6827682&View=%7B5D8F3E3B-2425-4CCB-953C-22E82242EC05%7D&Source=https%3A%2F%2Fpetco%2Esharepoint%2Ecom%2Fsites%2FAnalyticsCommunity%2FLists%2FPlatforms_Master%2FAllItems%2Easpx - - 'Keeo only the View Section - 'View=%7B5D8F3E3B-2425-4CCB-953C-22E82242EC05%7D - - 'Replace %7B with "{" & %7D with "}", you now have the View ID. - 'View={5D8F3E3B-2425-4CCB-953C-22E82242EC05} - - - Set ListObj = ActiveSheet.ListObjects.Add(SourceType:=xlSrcExternal, _ - Source:=Array(Server, ListName, ViewName), _ - XlListObjectHasHeaders:=xlYes, _ - LinkSource:=xlYes, _ - Destination:=Range("$A$21"), _ - TableStyleName:="TableStyleLight1") - - -End Sub - - -Sub SelectListObject() - - Dim LisObj As ListObject - - Set LisObj = ActiveSheet.ListObjects(2) - LisObj.Range.Select - LisObj.HeaderRowRange.Select - LisObj.DataBodyRange.Select - LisObj.TotalsRowRange.Select - -End Sub - - - +Sub CreateListObject() + + Dim ListObj As ListObject + Set ListObj = ActiveSheet.ListObjects.Add(SourceType:=xlSrcRange, _ + Source:=Range("$A$1:$C$5"), _ + XlListObjectHasHeaders:=xlNo, _ + Destination:=Range("$I$1"), _ + TableStyleName:="TableStyleLight1") + + 'PARMETER ONE: + 'SourceType:= xlSrcExternal, (External Data Connection) _ + xlSrcModel (PowerPivot Model), _ + xlSrcQuery (Query), _ + xlSrcRange (Range), _ + xlSrcXml (XML) + + 'PARAMTER TWO: + 'Source:= When SourceType equal xlSrcRange we need to pass through a range object. _ + If Omitted, then the source will default to the range returned by the list range _ + detection code. When SourceType equals xlSrcExternal an array of string values must be _ + passed through with the following three elements: _ + 0 - URL to SharePoint Site _ + 1 - ListName _ + 2 - View GUID + + 'PARAMETER THREE: + 'LinkSource:= Indicates whether an external data source is to be linked to the ListObject object. _ + If SourceType is xlSrcExternal, default is True. Invalid if SourceType is xlSrcRange , _ + and will return an error if not omitted. + + 'PARAMETER FOUR: + 'XlListObjectHasHeaders:= An xlYesNoGuess constant that indicates whether the data being imported has column labels. _ + If the Source does not contain headers, Excel will automatically generate headers. _ + Value Default: xlGuess. _ + Value Yes: xlYes. _ + Value No: xlNo. + + + 'PARAMETER FIVE: + 'Destination:= A Range object specifying a single-cell reference as the destination for the top-left corner of the new list object. _ + If the Range object refers to more than one cell, an error is generated. The Destination argument must be specified when SourceType is set to xlSrcExternal. _ + The Destination argument is ignored if SourceType is set to xlSrcRange. The destination range must be on the worksheet that _ + contains the ListObjects collection specified by expression. New columns will be inserted at the Destination to fit the new list. _ + Therefore, existing data will not be overwritten. + + 'PARAMETER SIX: + 'TableStyleName:= This is the name of a table style that we can apply to the table, in this example we used TableStyleLight1. + + +End Sub + +Sub CreateTableFromSharePointList() + + 'Declare Variables + Dim Server As String + Dim ListName As String + Dim ViewName As String + Dim ListObj As ListObject + + 'Get Connection String Paramaters + Server = "https://petco.sharepoint.com/sites/AnalyticsCommunity/_vti_bin" '<<< THIS IS YOUR SHAREPOINT SITE REPLACE WIT THE PROPER URL & MAKE SURE Vti_bin IS AT THE END. + ListName = "{6DC036F2-05F3-4EB9-A732-43E1C6827682}" '<<< This is the list name + ViewName = "{5D8F3E3B-2425-4CCB-953C-22E82242EC05}" '<<< This is the view name + + + 'TO GET THE LIST NAME/ID + 'Go To the List in SharePoin, click Settings & then right click "Audience Target Settings" + + 'Click Copy link address & Paste it in VBA. + 'https://petco.sharepoint.com/sites/AnalyticsCommunity/_layouts/ListEnableTargeting.aspx?List={6dc036f2-05f3-4eb9-a732-43e1c6827682} + + 'Delete Everything Before List & this is the List ID/Name: + 'List={6dc036f2-05f3-4eb9-a732-43e1c6827682} + + + 'TO GET THE VIEW ID + 'Go to the list in SharePoint, then the list section at the top of the ribbon, click modify view, & copy the URL on the new page. + 'https://petco.sharepoint.com/sites/AnalyticsCommunity/_layouts/15/ViewEdit.aspx?List=6dc036f2-05f3-4eb9-a732-43e1c6827682&View=%7B5D8F3E3B-2425-4CCB-953C-22E82242EC05%7D&Source=https%3A%2F%2Fpetco%2Esharepoint%2Ecom%2Fsites%2FAnalyticsCommunity%2FLists%2FPlatforms_Master%2FAllItems%2Easpx + + 'Keeo only the View Section + 'View=%7B5D8F3E3B-2425-4CCB-953C-22E82242EC05%7D + + 'Replace %7B with "{" & %7D with "}", you now have the View ID. + 'View={5D8F3E3B-2425-4CCB-953C-22E82242EC05} + + + Set ListObj = ActiveSheet.ListObjects.Add(SourceType:=xlSrcExternal, _ + Source:=Array(Server, ListName, ViewName), _ + XlListObjectHasHeaders:=xlYes, _ + LinkSource:=xlYes, _ + Destination:=Range("$A$21"), _ + TableStyleName:="TableStyleLight1") + + +End Sub + + +Sub SelectListObject() + + Dim LisObj As ListObject + + Set LisObj = ActiveSheet.ListObjects(2) + LisObj.Range.Select + LisObj.HeaderRowRange.Select + LisObj.DataBodyRange.Select + LisObj.TotalsRowRange.Select + +End Sub + + + diff --git a/vba/excel-vba/pivot-tables/Pivot Table - Part 1.bas b/vba/vba-excel/pivot-tables/Pivot Table Part 1.bas similarity index 96% rename from vba/excel-vba/pivot-tables/Pivot Table - Part 1.bas rename to vba/vba-excel/pivot-tables/Pivot Table Part 1.bas index 1523a0a..b67cf11 100644 --- a/vba/excel-vba/pivot-tables/Pivot Table - Part 1.bas +++ b/vba/vba-excel/pivot-tables/Pivot Table Part 1.bas @@ -1,63 +1,63 @@ -Sub CreatePivotTable() - -'Declare Variables -Dim PvtCache As PivotCache -Dim PvtTbl As PivotTable -Dim PvtFld As PivotField -Dim DataTbl As ListObject - -'Delete Pivot Table -ActiveSheet.PivotTables("MyNewPivotTable").TableRange2.Delete - -'Create a reference to the data source -Set DataTbl = Worksheets("Data_Table").ListObjects(1) - -'Create the Pivot Cache -Set PvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _ - SourceData:=DataTbl.Name, _ - Version:=6) - -'Create the Pivot Table -Set PvtTbl = PvtCache.CreatePivotTable(TableDestination:="Pivot_Table!R1C1", _ - TableName:="MyNewPivotTable", _ - DefaultVersion:=6) - -'Create a Row Field -With PvtTbl.PivotFields("Year") - .Orientation = xlRowField - .Position = 1 -End With - -'Create Another Row Field, this will be the inner one. -With PvtTbl.PivotFields("Country") - .Orientation = xlRowField - .Position = 2 -End With - -'Create a Column Field -With PvtTbl.PivotFields("Month Name") - .Orientation = xlColumnField - .Position = 1 -End With - -'Create a Data Field -With PvtTbl.PivotFields("COGS") - .Orientation = xlDataField - .Position = 1 -End With - -'Create a Filter Field -With PvtTbl.PivotFields("Product") - .Orientation = xlPageField - .Position = 1 -End With - -'Hide a field -Set PvtFld = PvtTbl.PivotFields("Month Name") - PvtFld.PivotItems("January").Visible = False - -'Change the Layout & Style -PvtTbl.RowAxisLayout xlTabularRow -PvtTbl.TableStyle2 = "PivotStyleLight24" - -End Sub +Sub CreatePivotTable() + +'Declare Variables +Dim PvtCache As PivotCache +Dim PvtTbl As PivotTable +Dim PvtFld As PivotField +Dim DataTbl As ListObject + +'Delete Pivot Table +ActiveSheet.PivotTables("MyNewPivotTable").TableRange2.Delete + +'Create a reference to the data source +Set DataTbl = Worksheets("Data_Table").ListObjects(1) + +'Create the Pivot Cache +Set PvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _ + SourceData:=DataTbl.Name, _ + Version:=6) + +'Create the Pivot Table +Set PvtTbl = PvtCache.CreatePivotTable(TableDestination:="Pivot_Table!R1C1", _ + TableName:="MyNewPivotTable", _ + DefaultVersion:=6) + +'Create a Row Field +With PvtTbl.PivotFields("Year") + .Orientation = xlRowField + .Position = 1 +End With + +'Create Another Row Field, this will be the inner one. +With PvtTbl.PivotFields("Country") + .Orientation = xlRowField + .Position = 2 +End With + +'Create a Column Field +With PvtTbl.PivotFields("Month Name") + .Orientation = xlColumnField + .Position = 1 +End With + +'Create a Data Field +With PvtTbl.PivotFields("COGS") + .Orientation = xlDataField + .Position = 1 +End With + +'Create a Filter Field +With PvtTbl.PivotFields("Product") + .Orientation = xlPageField + .Position = 1 +End With + +'Hide a field +Set PvtFld = PvtTbl.PivotFields("Month Name") + PvtFld.PivotItems("January").Visible = False + +'Change the Layout & Style +PvtTbl.RowAxisLayout xlTabularRow +PvtTbl.TableStyle2 = "PivotStyleLight24" + +End Sub diff --git a/vba/excel-vba/pivot-tables/Pivot Table - Part 2.bas b/vba/vba-excel/pivot-tables/Pivot Table Part 2.bas similarity index 96% rename from vba/excel-vba/pivot-tables/Pivot Table - Part 2.bas rename to vba/vba-excel/pivot-tables/Pivot Table Part 2.bas index 3105542..cede0a0 100644 --- a/vba/excel-vba/pivot-tables/Pivot Table - Part 2.bas +++ b/vba/vba-excel/pivot-tables/Pivot Table Part 2.bas @@ -1,116 +1,116 @@ -Sub CreatePivotTable() - -'Declare Variables -Dim PvtCache As PivotCache -Dim PvtTbl As PivotTable -Dim PvtFld As PivotField -Dim DataTbl As ListObject - -'Delete Pivot Table -ActiveSheet.PivotTables("MyNewPivotTable").TableRange2.Delete - -'Create a reference to the data table -Set DataTbl = Worksheets("Data_Table").ListObjects(1) - -'Create a Pivot Cache -Set PvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _ - SourceData:=DataTbl.Name, _ - Version:=6) - -'Create a Pivot Table -Set PvtTbl = PvtCache.CreatePivotTable(TableDestination:="Pivot_Table!R1C1", _ - TableName:="MyNewPivotTable", _ - DefaultVersion:=6) - -'Create a row field -With PvtTbl.PivotFields("Year") - .Orientation = xlRowField - .Position = 1 -End With - -'Create a row field -With PvtTbl.PivotFields("Country") - .Orientation = xlRowField - .Position = 2 -End With - -'Create a column field -With PvtTbl.PivotFields("Month Name") - .Orientation = xlColumnField - .Position = 1 -End With - -'Create a data field -With PvtTbl.PivotFields("COGS") - .Orientation = xlDataField - .Position = 1 -End With - -'Create a filter field -With PvtTbl.PivotFields("Product") - .Orientation = xlPageField - .Position = 1 -End With - -'Hide a pivot item -Set PvtFld = PvtTbl.PivotFields("Month Name") - PvtFld.PivotItems("March").Visible = False - -'Change the layout -PvtTbl.RowAxisLayout xlTabularRow - -'Change the color -PvtTbl.TableStyle2 = "PivotStyleLight24" - -'Create a calculate field -PvtTbl.CalculatedFields.Add "Average Selling Price", "=Gross Sales / Units Sold" - -'Create the field to house the calculated field -With PvtTbl.PivotFields("Average Selling Price") - .Orientation = xlDataField - .Position = 2 - .NumberFormat = "#,##0.00" -End With - -'Add a Calculated Field -PvtTbl.CalculatedFields.Add "Average Selling Price 2", "= Average Selling Price *.1" - -'Create a Data Field -With PvtTbl.PivotFields("Average Selling Price 2") - .Orientation = xlDataField - .Position = 3 - .NumberFormat = "#,##0.00" -End With - -'Add a Calculated Item -PvtTbl.PivotFields("Country").CalculatedItems.Add "North America", "=Canada + Mexico + United States of America" - - -'Get Pivot Data With VBA -Range("A22").Value = PvtTbl.GetPivotData("Sum Of COGS", "Country", "Canada", "Year", "2014", "Month Name", "April") - -'Get Data -Range("A23").Value = PvtTbl.GetData("Sum Of COGS Canada 2014 April") - -'Pivot Select VBA -PvtTbl.PivotSelect "Country['France'] Year['2013']", xlDataAndLabel - -'Selecting Different Parts of Our Pivot Table -PvtTbl.DataBodyRange.Select -PvtTbl.DataLabelRange.Select -PvtTbl.RowRange.Select -PvtTbl.ColumnRange.Select -PvtTbl.PageRange.Select -PvtTbl.TableRange1.Select -PvtTbl.TableRange2.Select - -'Clear all Filters -PvtTbl.PivotFields("Month Name").ClearAllFilters - -'Add a Top 2 Filter -PvtTbl.PivotFields("Month Name").PivotFilters.Add2 Type:=xlTopCount, DataField:=PvtTbl.PivotFields("Sum of COGS"), Value1:=2 - -'Add a Label Filter -PvtTbl.PivotFields("Month Name").PivotFilters.Add2 Type:=xlCaptionContains, Value1:="Feb" - -End Sub +Sub CreatePivotTable() + +'Declare Variables +Dim PvtCache As PivotCache +Dim PvtTbl As PivotTable +Dim PvtFld As PivotField +Dim DataTbl As ListObject + +'Delete Pivot Table +ActiveSheet.PivotTables("MyNewPivotTable").TableRange2.Delete + +'Create a reference to the data table +Set DataTbl = Worksheets("Data_Table").ListObjects(1) + +'Create a Pivot Cache +Set PvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _ + SourceData:=DataTbl.Name, _ + Version:=6) + +'Create a Pivot Table +Set PvtTbl = PvtCache.CreatePivotTable(TableDestination:="Pivot_Table!R1C1", _ + TableName:="MyNewPivotTable", _ + DefaultVersion:=6) + +'Create a row field +With PvtTbl.PivotFields("Year") + .Orientation = xlRowField + .Position = 1 +End With + +'Create a row field +With PvtTbl.PivotFields("Country") + .Orientation = xlRowField + .Position = 2 +End With + +'Create a column field +With PvtTbl.PivotFields("Month Name") + .Orientation = xlColumnField + .Position = 1 +End With + +'Create a data field +With PvtTbl.PivotFields("COGS") + .Orientation = xlDataField + .Position = 1 +End With + +'Create a filter field +With PvtTbl.PivotFields("Product") + .Orientation = xlPageField + .Position = 1 +End With + +'Hide a pivot item +Set PvtFld = PvtTbl.PivotFields("Month Name") + PvtFld.PivotItems("March").Visible = False + +'Change the layout +PvtTbl.RowAxisLayout xlTabularRow + +'Change the color +PvtTbl.TableStyle2 = "PivotStyleLight24" + +'Create a calculate field +PvtTbl.CalculatedFields.Add "Average Selling Price", "=Gross Sales / Units Sold" + +'Create the field to house the calculated field +With PvtTbl.PivotFields("Average Selling Price") + .Orientation = xlDataField + .Position = 2 + .NumberFormat = "#,##0.00" +End With + +'Add a Calculated Field +PvtTbl.CalculatedFields.Add "Average Selling Price 2", "= Average Selling Price *.1" + +'Create a Data Field +With PvtTbl.PivotFields("Average Selling Price 2") + .Orientation = xlDataField + .Position = 3 + .NumberFormat = "#,##0.00" +End With + +'Add a Calculated Item +PvtTbl.PivotFields("Country").CalculatedItems.Add "North America", "=Canada + Mexico + United States of America" + + +'Get Pivot Data With VBA +Range("A22").Value = PvtTbl.GetPivotData("Sum Of COGS", "Country", "Canada", "Year", "2014", "Month Name", "April") + +'Get Data +Range("A23").Value = PvtTbl.GetData("Sum Of COGS Canada 2014 April") + +'Pivot Select VBA +PvtTbl.PivotSelect "Country['France'] Year['2013']", xlDataAndLabel + +'Selecting Different Parts of Our Pivot Table +PvtTbl.DataBodyRange.Select +PvtTbl.DataLabelRange.Select +PvtTbl.RowRange.Select +PvtTbl.ColumnRange.Select +PvtTbl.PageRange.Select +PvtTbl.TableRange1.Select +PvtTbl.TableRange2.Select + +'Clear all Filters +PvtTbl.PivotFields("Month Name").ClearAllFilters + +'Add a Top 2 Filter +PvtTbl.PivotFields("Month Name").PivotFilters.Add2 Type:=xlTopCount, DataField:=PvtTbl.PivotFields("Sum of COGS"), Value1:=2 + +'Add a Label Filter +PvtTbl.PivotFields("Month Name").PivotFilters.Add2 Type:=xlCaptionContains, Value1:="Feb" + +End Sub diff --git a/vba/excel-vba/pivot-tables/Pivot Table - Part 3.bas b/vba/vba-excel/pivot-tables/Pivot Table Part 3.bas similarity index 97% rename from vba/excel-vba/pivot-tables/Pivot Table - Part 3.bas rename to vba/vba-excel/pivot-tables/Pivot Table Part 3.bas index 25c8bed..5a392dc 100644 --- a/vba/excel-vba/pivot-tables/Pivot Table - Part 3.bas +++ b/vba/vba-excel/pivot-tables/Pivot Table Part 3.bas @@ -1,79 +1,79 @@ -Sub PivotTablePart3() - -'Declare Variables -Dim PvtTbl As PivotTable -Dim PvtFlds As PivotFields -Dim PvtFld As PivotField - -'Reference the Pivot Table -Set PvtTbl = ActiveSheet.PivotTables("MyNewPivotTable") - -'Loop through each field in our collection -For Each PvtFld In PvtTbl.VisibleFields - Debug.Print PvtFld.Name - Debug.Print PvtFld.Value - Debug.Print PvtFld.DataType -Next - -'Create a reference to a single pivot field -Set PvtFld = PvtTbl.PivotFields("Year") - PvtFld.DragToColumn = False - PvtFld.DragToData = True - PvtFld.DragToHide = False - -'Get the detail for the cell -ActiveCell.ShowDetail = True - -'Declare more variables -Dim PvtAxs As PivotAxis -Dim PvtLns As PivotLines -Dim PvtLin As PivotLine - -'Reference an Axis of the Pivot Table -Set PvtAxs = PvtTbl.PivotRowAxis -Set PvtLns = PvtAxs.PivotLines - -'Loop through each line -For Each PvtLin In PvtLns - Debug.Print PvtLin.Position - Debug.Print PvtLin.LineType - Debug.Print PvtLin.Application -Next - -'xlPivotLineBlank 3 Blank line after each group. -'xlPivotLineGrandTotal 2 Grand Total line. -'xlPivotLineRegular 0 Regular PivotLine with pivot items. -'xlPivotLineSubtotal 1 Subtotal line. - -'Declare Variable -Dim PvtCell As PivotCell - -'Reference an individual Line -Set PvtLin = PvtLns.Item(3) - -'Loop through each Pivot cell in our line -For Each PvtCell In PvtLin.PivotLineCellsFull - Debug.Print PvtCell.Range - Debug.Print PvtCell.PivotTable - Debug.Print PvtCell.PivotCellType - Debug.Print PvtCell.PivotItem - Debug.Print PvtCell.PivotField -Next - -'xlPivotCellBlankCell 9 A structural blank cell in the PivotTable. -'xlPivotCellCustomSubtotal 7 A cell in the row or column area that is a custom subtotal. -'xlPivotCellDataField 4 A data field label (not the Data button). -'xlPivotCellDataPivotField 8 The Data button. -'xlPivotCellGrandTotal 3 A cell in a row or column area that is a grand total. -'xlPivotCellPageFieldItem 6 The cell that shows the selected item of a Page field. -'xlPivotCellPivotField 5 The button for a field (not the Data button). -'xlPivotCellPivotItem 1 A cell in the row or column area that is not a subtotal, grand total, custom subtotal, or blank line. -'xlPivotCellSubtotal 2 A cell in the row or column area that is a subtotal. -'xlPivotCellValue 0 Any cell in the data area (except a blank row). - -Debug.Print PvtTbl.PivotValueCell(3, 1).PivotCell.PivotCellType -Debug.Print PvtTbl.PivotValueCell(3, 1).Value - -PvtTbl.PivotValueCell(3, 1).ShowDetail - -End Sub +Sub PivotTablePart3() + +'Declare Variables +Dim PvtTbl As PivotTable +Dim PvtFlds As PivotFields +Dim PvtFld As PivotField + +'Reference the Pivot Table +Set PvtTbl = ActiveSheet.PivotTables("MyNewPivotTable") + +'Loop through each field in our collection +For Each PvtFld In PvtTbl.VisibleFields + Debug.Print PvtFld.Name + Debug.Print PvtFld.Value + Debug.Print PvtFld.DataType +Next + +'Create a reference to a single pivot field +Set PvtFld = PvtTbl.PivotFields("Year") + PvtFld.DragToColumn = False + PvtFld.DragToData = True + PvtFld.DragToHide = False + +'Get the detail for the cell +ActiveCell.ShowDetail = True + +'Declare more variables +Dim PvtAxs As PivotAxis +Dim PvtLns As PivotLines +Dim PvtLin As PivotLine + +'Reference an Axis of the Pivot Table +Set PvtAxs = PvtTbl.PivotRowAxis +Set PvtLns = PvtAxs.PivotLines + +'Loop through each line +For Each PvtLin In PvtLns + Debug.Print PvtLin.Position + Debug.Print PvtLin.LineType + Debug.Print PvtLin.Application +Next + +'xlPivotLineBlank 3 Blank line after each group. +'xlPivotLineGrandTotal 2 Grand Total line. +'xlPivotLineRegular 0 Regular PivotLine with pivot items. +'xlPivotLineSubtotal 1 Subtotal line. + +'Declare Variable +Dim PvtCell As PivotCell + +'Reference an individual Line +Set PvtLin = PvtLns.Item(3) + +'Loop through each Pivot cell in our line +For Each PvtCell In PvtLin.PivotLineCellsFull + Debug.Print PvtCell.Range + Debug.Print PvtCell.PivotTable + Debug.Print PvtCell.PivotCellType + Debug.Print PvtCell.PivotItem + Debug.Print PvtCell.PivotField +Next + +'xlPivotCellBlankCell 9 A structural blank cell in the PivotTable. +'xlPivotCellCustomSubtotal 7 A cell in the row or column area that is a custom subtotal. +'xlPivotCellDataField 4 A data field label (not the Data button). +'xlPivotCellDataPivotField 8 The Data button. +'xlPivotCellGrandTotal 3 A cell in a row or column area that is a grand total. +'xlPivotCellPageFieldItem 6 The cell that shows the selected item of a Page field. +'xlPivotCellPivotField 5 The button for a field (not the Data button). +'xlPivotCellPivotItem 1 A cell in the row or column area that is not a subtotal, grand total, custom subtotal, or blank line. +'xlPivotCellSubtotal 2 A cell in the row or column area that is a subtotal. +'xlPivotCellValue 0 Any cell in the data area (except a blank row). + +Debug.Print PvtTbl.PivotValueCell(3, 1).PivotCell.PivotCellType +Debug.Print PvtTbl.PivotValueCell(3, 1).Value + +PvtTbl.PivotValueCell(3, 1).ShowDetail + +End Sub diff --git a/vba/excel-vba/power-pivot/Power Pivot - Part 1.bas b/vba/vba-excel/power-pivot/Power Pivot Part 1.bas similarity index 97% rename from vba/excel-vba/power-pivot/Power Pivot - Part 1.bas rename to vba/vba-excel/power-pivot/Power Pivot Part 1.bas index 16d23bd..01d47e4 100644 --- a/vba/excel-vba/power-pivot/Power Pivot - Part 1.bas +++ b/vba/vba-excel/power-pivot/Power Pivot Part 1.bas @@ -1,64 +1,64 @@ -Sub ReferencePPM() -Dim myModel As Model - -Set myModel = ActiveWorkbook.Model - Debug.Print myModel.Application - Debug.Print myModel.Name - Debug.Print myModel.Creator - Debug.Print myModel.DataModelConnection - -End Sub - -Sub AddAConnection() - -WrkName = ActiveWorkbook.Name -TblName = Sheets("Price_Data").ListObjects(1).Name -FilPath = ActiveWorkbook.Path - -ConnStr = "WORKSHEET;" + FilPath -CommTxt = WrkName + "!" + TblName - -'"WORKSHEET;C:\Users\305197\Desktop\PowerPivot.xlsm" -Workbooks("PowerPivot.xlsm").Connections.Add2 _ - Name:="MyConnectionToData", _ - Description:="This is my price dataset.", _ - ConnectionString:=ConnStr, _ - CommandText:=CommTxt, _ - lCmdtype:=xlCmdExcel, _ - CreateModelConnection:=True, _ - ImportRelationships:=False - -End Sub - -Sub AddMeasureToPowerPivot() - -'Declare your variables. -Dim myModel As Model -Dim myModelTables As ModelTables -Dim myModelMeasures As ModelMeasures -Dim myModelTable As ModelTable - -'Create a reference to the PowerPivot Model -Set myModel = ActiveWorkbook.Model - -'Create a reference to the ModelTables collection. -Set myModelTables = myModel.ModelTables - -'Now that we have a reference to the collection, let's select one of our tables using the item Method. -Set myModelTable = myModelTables.Item(1) - -'We could have also used this method. -'Set myModelTable = myModel.ModelTables.Item(1) - -'Let's create a new measure in our PowerPivot Model. First we need to create a reference to -'the Model Measures collection -Set myModelMeasures = myModel.ModelMeasures - - 'We can now call the add method to add a new measure. - myModelMeasures.Add MeasureName:="TotalTransactionCount", _ - AssociatedTable:=myModelTable, _ - Formula:="Sum(Table1[Transaction])", _ - FormatInformation:=myModel.ModelFormatDecimalNumber, _ - Description:="This is count of all my transactions." - -End Sub +Sub ReferencePPM() +Dim myModel As Model + +Set myModel = ActiveWorkbook.Model + Debug.Print myModel.Application + Debug.Print myModel.Name + Debug.Print myModel.Creator + Debug.Print myModel.DataModelConnection + +End Sub + +Sub AddAConnection() + +WrkName = ActiveWorkbook.Name +TblName = Sheets("Price_Data").ListObjects(1).Name +FilPath = ActiveWorkbook.Path + +ConnStr = "WORKSHEET;" + FilPath +CommTxt = WrkName + "!" + TblName + +'"WORKSHEET;C:\Users\305197\Desktop\PowerPivot.xlsm" +Workbooks("PowerPivot.xlsm").Connections.Add2 _ + Name:="MyConnectionToData", _ + Description:="This is my price dataset.", _ + ConnectionString:=ConnStr, _ + CommandText:=CommTxt, _ + lCmdtype:=xlCmdExcel, _ + CreateModelConnection:=True, _ + ImportRelationships:=False + +End Sub + +Sub AddMeasureToPowerPivot() + +'Declare your variables. +Dim myModel As Model +Dim myModelTables As ModelTables +Dim myModelMeasures As ModelMeasures +Dim myModelTable As ModelTable + +'Create a reference to the PowerPivot Model +Set myModel = ActiveWorkbook.Model + +'Create a reference to the ModelTables collection. +Set myModelTables = myModel.ModelTables + +'Now that we have a reference to the collection, let's select one of our tables using the item Method. +Set myModelTable = myModelTables.Item(1) + +'We could have also used this method. +'Set myModelTable = myModel.ModelTables.Item(1) + +'Let's create a new measure in our PowerPivot Model. First we need to create a reference to +'the Model Measures collection +Set myModelMeasures = myModel.ModelMeasures + + 'We can now call the add method to add a new measure. + myModelMeasures.Add MeasureName:="TotalTransactionCount", _ + AssociatedTable:=myModelTable, _ + Formula:="Sum(Table1[Transaction])", _ + FormatInformation:=myModel.ModelFormatDecimalNumber, _ + Description:="This is count of all my transactions." + +End Sub diff --git a/vba/excel-vba/power-pivot/Power Pivot - Part 2.bas b/vba/vba-excel/power-pivot/Power Pivot Part 2.bas similarity index 100% rename from vba/excel-vba/power-pivot/Power Pivot - Part 2.bas rename to vba/vba-excel/power-pivot/Power Pivot Part 2.bas diff --git a/vba/excel-vba/power-pivot/Power Pivot - Part 3.bas b/vba/vba-excel/power-pivot/Power Pivot Part 3.bas similarity index 100% rename from vba/excel-vba/power-pivot/Power Pivot - Part 3.bas rename to vba/vba-excel/power-pivot/Power Pivot Part 3.bas diff --git a/vba/excel-vba/power-query/Import Text File.bas b/vba/vba-excel/power-query/Power Query - Import Text File.bas similarity index 97% rename from vba/excel-vba/power-query/Import Text File.bas rename to vba/vba-excel/power-query/Power Query - Import Text File.bas index e39f4a3..e00f72c 100644 --- a/vba/excel-vba/power-query/Import Text File.bas +++ b/vba/vba-excel/power-query/Power Query - Import Text File.bas @@ -1,46 +1,46 @@ -Attribute VB_Name = "ImportTextFilePowerQuery" -Option Explicit - -Sub ImportTextFile() - -'Declare Our Variables -Dim QueryName, SourceFormula, ConnStr As String - -'Create a New Active Query, define the name and the formula -QueryName = "SalesDataPull" -SourceFormula = "let Source = Csv.Document(File.Contents(""C:\Users\Alex\Desktop\SalesData.txt""), " & _ - "[Delimiter=""#(tab)"", " & _ - "Columns=5, " & _ - "Encoding=1200, " & _ - "QuoteStyle=QuoteStyle.None]), " & _ - "#""Promoted Headers"" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]), " & _ - "#""Changed Type"" = Table.TransformColumnTypes(#""Promoted Headers"",{{""FY"", Int64.Type}, " & _ - "{""Per"", Int64.Type}, {""Jrnl Dt"", Int64.Type}, {""Amount"", type number}, {""Acct Descr"", type text}}) in #""Changed Type""" - -'Add that new query to the workbook. -ActiveWorkbook.Queries.Add Name:=QueryName, _ - Formula:=SourceFormula, _ - Description:="This query will pull my sales data" - -'Create the connection string -ConnStr = "OLEDB;" & _ - "Provider=Microsoft.Mashup.OleDb.1;" & _ - "Data Source=$Workbook$;" & _ - "Location=""SalesDataPull"";" & _ - "Extended Properties=""""" - -'Add a Query Table to our Worksheet -With ActiveSheet.ListObjects.Add(SourceType:=xlSrcExternal, _ - LinkSource:=True, _ - xlListObjectHasHeaders:=xlYes, _ - Source:=ConnStr, _ - Destination:=Range("$A$1")).QueryTable - .CommandType = xlCmdSql - .CommandText = Array("SELECT * FROM [SalesDataPull]") - .Refresh BackgroundQuery:=False -End With - -End Sub - - - +Attribute VB_Name = "ImportTextFilePowerQuery" +Option Explicit + +Sub ImportTextFile() + +'Declare Our Variables +Dim QueryName, SourceFormula, ConnStr As String + +'Create a New Active Query, define the name and the formula +QueryName = "SalesDataPull" +SourceFormula = "let Source = Csv.Document(File.Contents(""C:\Users\Alex\Desktop\SalesData.txt""), " & _ + "[Delimiter=""#(tab)"", " & _ + "Columns=5, " & _ + "Encoding=1200, " & _ + "QuoteStyle=QuoteStyle.None]), " & _ + "#""Promoted Headers"" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]), " & _ + "#""Changed Type"" = Table.TransformColumnTypes(#""Promoted Headers"",{{""FY"", Int64.Type}, " & _ + "{""Per"", Int64.Type}, {""Jrnl Dt"", Int64.Type}, {""Amount"", type number}, {""Acct Descr"", type text}}) in #""Changed Type""" + +'Add that new query to the workbook. +ActiveWorkbook.Queries.Add Name:=QueryName, _ + Formula:=SourceFormula, _ + Description:="This query will pull my sales data" + +'Create the connection string +ConnStr = "OLEDB;" & _ + "Provider=Microsoft.Mashup.OleDb.1;" & _ + "Data Source=$Workbook$;" & _ + "Location=""SalesDataPull"";" & _ + "Extended Properties=""""" + +'Add a Query Table to our Worksheet +With ActiveSheet.ListObjects.Add(SourceType:=xlSrcExternal, _ + LinkSource:=True, _ + xlListObjectHasHeaders:=xlYes, _ + Source:=ConnStr, _ + Destination:=Range("$A$1")).QueryTable + .CommandType = xlCmdSql + .CommandText = Array("SELECT * FROM [SalesDataPull]") + .Refresh BackgroundQuery:=False +End With + +End Sub + + + diff --git a/vba/excel-vba/power-query/Query Table Info.bas b/vba/vba-excel/power-query/Power Query - Query Table Object.bas similarity index 97% rename from vba/excel-vba/power-query/Query Table Info.bas rename to vba/vba-excel/power-query/Power Query - Query Table Object.bas index 78abad4..fa6d5f8 100644 --- a/vba/excel-vba/power-query/Query Table Info.bas +++ b/vba/vba-excel/power-query/Power Query - Query Table Object.bas @@ -1,37 +1,37 @@ -Option Explicit - -Sub GetInfoAboutMyQueryTable() - -With ActiveSheet.ListObjects(1) - - 'Use the SourceDataFile Property to get the path to the source data file. - MsgBox .QueryTable.SourceDataFile - - 'Use the SourceConnectionFile Property to get the path to the connection file you exported. - MsgBox .QueryTable.SourceConnectionFile - - 'Use the Connection Property to find out the connection string used in this QueryTable. - MsgBox .QueryTable.Connection - - 'Use the Creator Property -- USED FOR MACS -- To see which application created this QueryTable. - MsgBox .QueryTable.Creator - - 'Get the workbook connection used in this QueryTable - MsgBox .QueryTable.WorkbookConnection - - 'Get the Result Range of My Query. - MsgBox .QueryTable.ResultRange.Address - - 'Get the QueryType of My Query - MsgBox .QueryTable.QueryType - - 'xlADORecordset 7 Based on an ADO recordset query - 'xlDAORecordset 2 Based on a DAO recordset query, for query tables only - 'xlODBCQuery 1 Based on an ODBC data source - 'xlOLEDBQuery 5 Based on an OLE DB query, including OLAP data sources - 'xlTextImport 6 Based on a text file, for query tables only - 'xlWebQuery 4 Based on a Web page, for query tables only - -End With - -End Sub +Option Explicit + +Sub GetInfoAboutMyQueryTable() + +With ActiveSheet.ListObjects(1) + + 'Use the SourceDataFile Property to get the path to the source data file. + MsgBox .QueryTable.SourceDataFile + + 'Use the SourceConnectionFile Property to get the path to the connection file you exported. + MsgBox .QueryTable.SourceConnectionFile + + 'Use the Connection Property to find out the connection string used in this QueryTable. + MsgBox .QueryTable.Connection + + 'Use the Creator Property -- USED FOR MACS -- To see which application created this QueryTable. + MsgBox .QueryTable.Creator + + 'Get the workbook connection used in this QueryTable + MsgBox .QueryTable.WorkbookConnection + + 'Get the Result Range of My Query. + MsgBox .QueryTable.ResultRange.Address + + 'Get the QueryType of My Query + MsgBox .QueryTable.QueryType + + 'xlADORecordset 7 Based on an ADO recordset query + 'xlDAORecordset 2 Based on a DAO recordset query, for query tables only + 'xlODBCQuery 1 Based on an ODBC data source + 'xlOLEDBQuery 5 Based on an OLE DB query, including OLAP data sources + 'xlTextImport 6 Based on a text file, for query tables only + 'xlWebQuery 4 Based on a Web page, for query tables only + +End With + +End Sub diff --git a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Book.bas b/vba/vba-excel/range/Selecting Ranges - Book.bas similarity index 97% rename from vba/excel-vba/core-concepts/ranges/Selecting Ranges - Book.bas rename to vba/vba-excel/range/Selecting Ranges - Book.bas index 7d2898e..43c8488 100644 --- a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Book.bas +++ b/vba/vba-excel/range/Selecting Ranges - Book.bas @@ -1,78 +1,78 @@ -Attribute VB_Name = "Module1" -Sub SelectingRanges_ObjectHierarchy() - - 'The most explicit way to reference a range of cells. - Application.Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("A1").Select - - 'Still very explict but can be confusing for sure because we need to keep in mind whether we have a personal macro workbook or not - Application.Workbooks(2).Worksheets(1).Range("B1").Select - - 'Less Explicit, ThisWorkbook is referring to the workbook that contains our subroutine - Application.ThisWorkbook.Worksheets(1).Range("C1").Select - - 'Less Explicit, ActiveWorkbook is referring to the workbook that is open and we see. - Application.ActiveWorkbook.Worksheets(1).Range("B1").Select - - - 'We can even be less explicit in our code, but then VBA will fill in the blanks. Which is a good and bad. - - - 'Forget the application - Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("A2").Select '<<< This is how it looks in VBA's eyes Application.Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("B1").Select - - 'Forget the workbook - Worksheets("Sheet1").Range("A2").Select '<<< This is how it looks in VBA's eyes Application.ActiveWorkbook.Worksheets("Sheet1").Range("B1").Select - - 'Forget the worksheet - 'Range("A2").Select '<<< This is how it looks in VBA's eyes Application.ActiveWorkbook.ActiveWorksheet.Range("A2").Select - - - 'If you use the Select method to select cells, be aware that Select works only on the active worksheet. - -End Sub - - -Sub SelectingWorkbooks() - - ' The application object has a collection that houses all of our workbooks, its called "WORKBOOKS" - ' To access this collection, we call the Application and then the property Workbooks. - ' This collection does not contain add-in workbooks (.xla) and workbooks in protected view are not a member of this collection. - - ' --- "Application.Workbooks" - - ' If we don't use an object qualifier for this property it's equivalent to using "Application.Workbooks" - - ' --- "Workbooks" is the same as "Application.Workbooks" we just are dropping the "Application" object. - - - ' SELECTING INDIVIDUAL WORKBOOKS FROM THE WORKBOOK COLLECTIONS - - ' The Explict way - Using the KEY METHOD - Application.Workbooks("SelectingWorkbooks.xlsx").Activate - Application.Workbooks("SelectingWorkbooks2.xlsx").Activate - ' Workbooks("SelectingWorkbooks.xlsx").Activate <<< Also Works - ' Workbooks("SelectingWorkbooks2.xlsx").Activate <<< Also Works - - ' The Less Explict way - Using the INDEX METHOD. - ' NOTE ONE: Index is determined by the order in which my workbooks were open. - ' NOTE TWO: If you have a PERSONAL.XSLB then this is ALSO a workbook in your collection and it is ALWAYS OPENED FIRST - - Application.Workbooks(1).Activate '<<< This is my Personal Macro Workbook and this workbook is ALWAYS OPENED FIRST - Application.Workbooks(2).Activate '<<< This is my workbook that was opened SECOND and it is named "SelectingWorkbooks.xlsx" - Application.Workbooks(3).Activate '<<< This is my workbook that was opened THIRD and it is named "SelectingWorkbooks2.xlsx" - ' Workbooks(1).Activate '<<< Also Works - ' Workbooks(2).Activate '<<< Also Works - ' Workbooks(3).Activate '<<< Also Works - - - ' Using the ActiveWorkbook Method - ' NOTE ONE: The ActiveWorkbook is the one that is opened and we can see on our screen. - ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 - - ' Using the ThisWorkbook Method - ' NOTE ONE: The ThisWorkbook is the one that houses our code. - ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 - - -End Sub - +Attribute VB_Name = "Module1" +Sub SelectingRanges_ObjectHierarchy() + + 'The most explicit way to reference a range of cells. + Application.Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("A1").Select + + 'Still very explict but can be confusing for sure because we need to keep in mind whether we have a personal macro workbook or not + Application.Workbooks(2).Worksheets(1).Range("B1").Select + + 'Less Explicit, ThisWorkbook is referring to the workbook that contains our subroutine + Application.ThisWorkbook.Worksheets(1).Range("C1").Select + + 'Less Explicit, ActiveWorkbook is referring to the workbook that is open and we see. + Application.ActiveWorkbook.Worksheets(1).Range("B1").Select + + + 'We can even be less explicit in our code, but then VBA will fill in the blanks. Which is a good and bad. + + + 'Forget the application + Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("A2").Select '<<< This is how it looks in VBA's eyes Application.Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("B1").Select + + 'Forget the workbook + Worksheets("Sheet1").Range("A2").Select '<<< This is how it looks in VBA's eyes Application.ActiveWorkbook.Worksheets("Sheet1").Range("B1").Select + + 'Forget the worksheet + 'Range("A2").Select '<<< This is how it looks in VBA's eyes Application.ActiveWorkbook.ActiveWorksheet.Range("A2").Select + + + 'If you use the Select method to select cells, be aware that Select works only on the active worksheet. + +End Sub + + +Sub SelectingWorkbooks() + + ' The application object has a collection that houses all of our workbooks, its called "WORKBOOKS" + ' To access this collection, we call the Application and then the property Workbooks. + ' This collection does not contain add-in workbooks (.xla) and workbooks in protected view are not a member of this collection. + + ' --- "Application.Workbooks" + + ' If we don't use an object qualifier for this property it's equivalent to using "Application.Workbooks" + + ' --- "Workbooks" is the same as "Application.Workbooks" we just are dropping the "Application" object. + + + ' SELECTING INDIVIDUAL WORKBOOKS FROM THE WORKBOOK COLLECTIONS + + ' The Explict way - Using the KEY METHOD + Application.Workbooks("SelectingWorkbooks.xlsx").Activate + Application.Workbooks("SelectingWorkbooks2.xlsx").Activate + ' Workbooks("SelectingWorkbooks.xlsx").Activate <<< Also Works + ' Workbooks("SelectingWorkbooks2.xlsx").Activate <<< Also Works + + ' The Less Explict way - Using the INDEX METHOD. + ' NOTE ONE: Index is determined by the order in which my workbooks were open. + ' NOTE TWO: If you have a PERSONAL.XSLB then this is ALSO a workbook in your collection and it is ALWAYS OPENED FIRST + + Application.Workbooks(1).Activate '<<< This is my Personal Macro Workbook and this workbook is ALWAYS OPENED FIRST + Application.Workbooks(2).Activate '<<< This is my workbook that was opened SECOND and it is named "SelectingWorkbooks.xlsx" + Application.Workbooks(3).Activate '<<< This is my workbook that was opened THIRD and it is named "SelectingWorkbooks2.xlsx" + ' Workbooks(1).Activate '<<< Also Works + ' Workbooks(2).Activate '<<< Also Works + ' Workbooks(3).Activate '<<< Also Works + + + ' Using the ActiveWorkbook Method + ' NOTE ONE: The ActiveWorkbook is the one that is opened and we can see on our screen. + ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 + + ' Using the ThisWorkbook Method + ' NOTE ONE: The ThisWorkbook is the one that houses our code. + ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 + + +End Sub + diff --git a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Last.bas b/vba/vba-excel/range/Selecting Ranges - Last.bas similarity index 96% rename from vba/excel-vba/core-concepts/ranges/Selecting Ranges - Last.bas rename to vba/vba-excel/range/Selecting Ranges - Last.bas index 7208478..e79e845 100644 --- a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Last.bas +++ b/vba/vba-excel/range/Selecting Ranges - Last.bas @@ -1,72 +1,72 @@ -Attribute VB_Name = "SelectingLast" - -Sub SelectingLastCellOfContiguousRange() - - 'Go To last cell - ActiveSheet.Range("a1").End(xlDown).Select - -End Sub - -Sub SelectingBlankCellOfContiguousRange() - - 'Go to first blank cell after laste cell - ActiveSheet.Range("a1").End(xlDown).Offset(1, 0).Select - -End Sub - -Sub SelectEntireRangeofContiguousCells() - - 'Select Range Of Cells No Blanks - ActiveSheet.Range("a1", ActiveSheet.Range("a1").End(xlDown)).Select - ActiveSheet.Range("a1:" & ActiveSheet.Range("a1").End(xlDown).Address).Select - -End Sub - -Sub SelectEntireRangeofNonContiguousCells() - - 'Select Range of Cells That Includes Blanks - ActiveSheet.Range("a1", ActiveSheet.Range("a65536").End(xlUp)).Select - ActiveSheet.Range("a1:" & ActiveSheet.Range("a65536").End(xlUp).Address).Select - -End Sub - -Sub SelectEntire() - - 'Select Entire Row - Range("1:1").Select - - 'Select Entire Column - Range("A:A").Select - -End Sub - - -Sub SelectRectangularRange() - -'Select Current Region -'ActiveSheet.Range("a1").CurrentRegion.Select -'ActiveSheet.Range("a1", ActiveSheet.Range("a1").End(xlDown).End(xlToRight)).Select -'ActiveSheet.Range("a1:" & ActiveSheet.Range("a1").End(xlDown).End(xlToRight).Address).Select - -'Build Current Region -lastCol = ActiveSheet.Range("a1").End(xlToRight).Column -lastRow = ActiveSheet.Cells(65536, lastCol).End(xlUp).Row -ActiveSheet.Range("a1", ActiveSheet.Cells(lastRow, lastCol)).Select - -'Including a blank row -lastCol = ActiveSheet.Range("a1").End(xlToRight).Column -lastRow = ActiveSheet.Cells(65536, lastCol).End(xlUp).Row -ActiveSheet.Range("a1:" & ActiveSheet.Cells(lastRow, lastCol).Address).Select - -End Sub - - -Sub SelectMultiNonContColumns() - -StartRange = "A1" -EndRange = "C1" -Set a = Range(StartRange, Range(StartRange).End(xlDown)) -Set b = Range(EndRange, Range(EndRange).End(xlDown)) -Union(a, b).Select - -End Sub +Attribute VB_Name = "SelectingLast" + +Sub SelectingLastCellOfContiguousRange() + + 'Go To last cell + ActiveSheet.Range("a1").End(xlDown).Select + +End Sub + +Sub SelectingBlankCellOfContiguousRange() + + 'Go to first blank cell after laste cell + ActiveSheet.Range("a1").End(xlDown).Offset(1, 0).Select + +End Sub + +Sub SelectEntireRangeofContiguousCells() + + 'Select Range Of Cells No Blanks + ActiveSheet.Range("a1", ActiveSheet.Range("a1").End(xlDown)).Select + ActiveSheet.Range("a1:" & ActiveSheet.Range("a1").End(xlDown).Address).Select + +End Sub + +Sub SelectEntireRangeofNonContiguousCells() + + 'Select Range of Cells That Includes Blanks + ActiveSheet.Range("a1", ActiveSheet.Range("a65536").End(xlUp)).Select + ActiveSheet.Range("a1:" & ActiveSheet.Range("a65536").End(xlUp).Address).Select + +End Sub + +Sub SelectEntire() + + 'Select Entire Row + Range("1:1").Select + + 'Select Entire Column + Range("A:A").Select + +End Sub + + +Sub SelectRectangularRange() + +'Select Current Region +'ActiveSheet.Range("a1").CurrentRegion.Select +'ActiveSheet.Range("a1", ActiveSheet.Range("a1").End(xlDown).End(xlToRight)).Select +'ActiveSheet.Range("a1:" & ActiveSheet.Range("a1").End(xlDown).End(xlToRight).Address).Select + +'Build Current Region +lastCol = ActiveSheet.Range("a1").End(xlToRight).Column +lastRow = ActiveSheet.Cells(65536, lastCol).End(xlUp).Row +ActiveSheet.Range("a1", ActiveSheet.Cells(lastRow, lastCol)).Select + +'Including a blank row +lastCol = ActiveSheet.Range("a1").End(xlToRight).Column +lastRow = ActiveSheet.Cells(65536, lastCol).End(xlUp).Row +ActiveSheet.Range("a1:" & ActiveSheet.Cells(lastRow, lastCol).Address).Select + +End Sub + + +Sub SelectMultiNonContColumns() + +StartRange = "A1" +EndRange = "C1" +Set a = Range(StartRange, Range(StartRange).End(xlDown)) +Set b = Range(EndRange, Range(EndRange).End(xlDown)) +Union(a, b).Select + +End Sub diff --git a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Offset.bas b/vba/vba-excel/range/Selecting Ranges - Offset.bas similarity index 95% rename from vba/excel-vba/core-concepts/ranges/Selecting Ranges - Offset.bas rename to vba/vba-excel/range/Selecting Ranges - Offset.bas index 32edcb6..ca35985 100644 --- a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Offset.bas +++ b/vba/vba-excel/range/Selecting Ranges - Offset.bas @@ -1,77 +1,75 @@ -Attribute VB_Name = "Offset" -Sub OffsetActiveCell() - -'Go 5 rows below & 4 columns to the left -ActiveCell.Offset(5, -4).Select - -'Go 2 rows above & 3 columns to the right -ActiveCell.Offset(-2, 3).Select - -'Error occurs if the row you're selecting is off the sheet. - -End Sub - -Sub OffsetCell() - -'Go 5 rows below & 4 columns to the right -ActiveSheet.Cells(7, 3).Offset(5, 4).Select - -'Go 5 rows below & 4 columns to the right -ActiveSheet.Range("C7").Offset(5, 4).Select - -End Sub - - -Sub OffsetRangeOfCell() - -'Go 4 rows below & 3 columns to the right - MAINTAING THE SAME RANGE SIZE -ActiveSheet.Range("Test").Offset(4, 3).Select - -'Long handed way -'Go 4 rows below & 3 columns to the right - MAINTAING THE SAME RANGE SIZE -Sheets("Sheet2").Activate -ActiveSheet.Range("Test").Offset(4, 3).Select - -End Sub - -Sub ResizeSelection() - -'Select the range -Range("Test").Select - -'Resize the selection by five rows -Selection.Resize(Selection.Rows.Count + 5, Selection.Columns.Count).Select - -End Sub - - -Sub ResizeSelectionOffset() - -'Select the range -Range("Test").Select - -'Offset and then resize the selection by five rows -Selection.Offset(4, 3).Resize(Selection.Rows.Count + 5, Selection.Columns.Count).Select - -End Sub - - -Sub SelectUnionOfTwoOrMoreRanges() - -Application.Union(Range("Test"), Range("Sample")).Select - -'DOES NOT WORK ACROSS SHEETS -Set y = Application.Union(Range("Sheet1!A1:B2"), Range("Sheet1!C3:D4")) -Set y = Application.Union(Range("Sheet1!A1:B2"), Range("Sheet2!C3:D4")) - - -End Sub - - - -Sub SelectIntersection() - -'DOES NOT WORK ACROSS SHEETS -Application.Intersect(Range("Test"), Range("Sample")).Select - -End Sub +Attribute VB_Name = "Offset" +Sub OffsetActiveCell() + +'Go 5 rows below & 4 columns to the left +ActiveCell.Offset(5, -4).Select + +'Go 2 rows above & 3 columns to the right +ActiveCell.Offset(-2, 3).Select + +'Error occurs if the row you're selecting is off the sheet. + +End Sub + +Sub OffsetCell() + +'Go 5 rows below & 4 columns to the right +ActiveSheet.Cells(7, 3).Offset(5, 4).Select + +'Go 5 rows below & 4 columns to the right +ActiveSheet.Range("C7").Offset(5, 4).Select + +End Sub + + +Sub OffsetRangeOfCell() + +'Go 4 rows below & 3 columns to the right - MAINTAING THE SAME RANGE SIZE +ActiveSheet.Range("Test").Offset(4, 3).Select + +'Long handed way +'Go 4 rows below & 3 columns to the right - MAINTAING THE SAME RANGE SIZE +Sheets("Sheet2").Activate +ActiveSheet.Range("Test").Offset(4, 3).Select + +End Sub + +Sub ResizeSelection() + +'Select the range +Range("Test").Select + +'Resize the selection by five rows +Selection.Resize(Selection.Rows.Count + 5, Selection.Columns.Count).Select + +End Sub + + +Sub ResizeSelectionOffset() + +'Select the range +Range("Test").Select + +'Offset and then resize the selection by five rows +Selection.Offset(4, 3).Resize(Selection.Rows.Count + 5, Selection.Columns.Count).Select + +End Sub + + +Sub SelectUnionOfTwoOrMoreRanges() + +Application.Union(Range("Test"), Range("Sample")).Select + +'DOES NOT WORK ACROSS SHEETS +Set y = Application.Union(Range("Sheet1!A1:B2"), Range("Sheet1!C3:D4")) +Set y = Application.Union(Range("Sheet1!A1:B2"), Range("Sheet2!C3:D4")) + +End Sub + + +Sub SelectIntersection() + +'DOES NOT WORK ACROSS SHEETS +Application.Intersect(Range("Test"), Range("Sample")).Select + +End Sub diff --git a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Selecting Cells.bas b/vba/vba-excel/range/Selecting Ranges - Selecting Cells.bas similarity index 96% rename from vba/excel-vba/core-concepts/ranges/Selecting Ranges - Selecting Cells.bas rename to vba/vba-excel/range/Selecting Ranges - Selecting Cells.bas index 4bb003b..7fc833a 100644 --- a/vba/excel-vba/core-concepts/ranges/Selecting Ranges - Selecting Cells.bas +++ b/vba/vba-excel/range/Selecting Ranges - Selecting Cells.bas @@ -1,77 +1,77 @@ -Attribute VB_Name = "SelectingCells" -Sub SelectCellOnActiveSheet() - - ActiveSheet.Cells(2, 2).Select - ActiveSheet.Range("B3").Select - -End Sub - -Sub SelectCellOnDifferentSheet() - - Application.Goto ActiveWorkbook.Sheets("Sheet2").Cells(6, 5) - Application.Goto (ActiveWorkbook.Sheets("Sheet2").Range("E6")) - - 'The Long handed way - 'Sheets("Sheet2").Activate - 'ActiveSheet.Cells(6, 5).Select - -End Sub - -Sub SelectCellInDifferentWorkbook() - - Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Cells(7, 6) - Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Range("F7") - - 'The Long handed way - 'Workbooks("BOOK2.xlsx").Sheets("Sheet1").Activate - 'ActiveSheet.Cells(7, 6).Select - -End Sub - -Sub SelectRangeOfCells() - - ActiveSheet.Range(Cells(2, 3), Cells(10, 4)).Select - ActiveSheet.Range("C2:D10").Select - ActiveSheet.Range("C2", "D10").Select - -End Sub - -Sub SelectRangeOfCellsDifferentSheet() - - Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("D3:E11") - Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("D3", "E11") - - 'The Long handed way - 'Sheets("Sheet3").Activate - 'ActiveSheet.Range(Cells(3, 4), Cells(11, 5)).Select - -End Sub - -Sub SelectRangeOfCellsDifferentWorkbook() - - Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Range("E4:F12") - Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Range("E4", "F12") - - 'The Long handed way - 'Workbooks("BOOK2.xlsx").Sheets("Sheet1").Activate - 'ActiveSheet.Range(Cells(4, 5), Cells(12, 6)).Select - -End Sub - -Sub SelectingNamedRange() - - 'ActiveSheet - Range("Test").Select - 'Application.Goto "Test" - - 'Different Worksheet, Same Workbook - Application.Goto Sheets("Sheet1").Range("Test2") - 'Sheets("Sheet1").Activate - 'Range("Test2").Select - - 'Different Worksheet, Different Workbook - Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet2").Range("Test") - 'Workbooks("BOOK2.xlsx").Sheets("Sheet2").Activate - 'ActiveSheet.Range("Test").Select - -End Sub +Attribute VB_Name = "SelectingCells" +Sub SelectCellOnActiveSheet() + + ActiveSheet.Cells(2, 2).Select + ActiveSheet.Range("B3").Select + +End Sub + +Sub SelectCellOnDifferentSheet() + + Application.Goto ActiveWorkbook.Sheets("Sheet2").Cells(6, 5) + Application.Goto (ActiveWorkbook.Sheets("Sheet2").Range("E6")) + + 'The Long handed way + 'Sheets("Sheet2").Activate + 'ActiveSheet.Cells(6, 5).Select + +End Sub + +Sub SelectCellInDifferentWorkbook() + + Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Cells(7, 6) + Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Range("F7") + + 'The Long handed way + 'Workbooks("BOOK2.xlsx").Sheets("Sheet1").Activate + 'ActiveSheet.Cells(7, 6).Select + +End Sub + +Sub SelectRangeOfCells() + + ActiveSheet.Range(Cells(2, 3), Cells(10, 4)).Select + ActiveSheet.Range("C2:D10").Select + ActiveSheet.Range("C2", "D10").Select + +End Sub + +Sub SelectRangeOfCellsDifferentSheet() + + Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("D3:E11") + Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("D3", "E11") + + 'The Long handed way + 'Sheets("Sheet3").Activate + 'ActiveSheet.Range(Cells(3, 4), Cells(11, 5)).Select + +End Sub + +Sub SelectRangeOfCellsDifferentWorkbook() + + Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Range("E4:F12") + Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet1").Range("E4", "F12") + + 'The Long handed way + 'Workbooks("BOOK2.xlsx").Sheets("Sheet1").Activate + 'ActiveSheet.Range(Cells(4, 5), Cells(12, 6)).Select + +End Sub + +Sub SelectingNamedRange() + + 'ActiveSheet + Range("Test").Select + 'Application.Goto "Test" + + 'Different Worksheet, Same Workbook + Application.Goto Sheets("Sheet1").Range("Test2") + 'Sheets("Sheet1").Activate + 'Range("Test2").Select + + 'Different Worksheet, Different Workbook + Application.Goto Workbooks("BOOK2.xlsx").Sheets("Sheet2").Range("Test") + 'Workbooks("BOOK2.xlsx").Sheets("Sheet2").Activate + 'ActiveSheet.Range("Test").Select + +End Sub diff --git a/vba/excel-vba/core-concepts/Loop Through Sheets And Books.bas b/vba/vba-excel/workbook/Loop Through Sheets And Books.bas similarity index 96% rename from vba/excel-vba/core-concepts/Loop Through Sheets And Books.bas rename to vba/vba-excel/workbook/Loop Through Sheets And Books.bas index bfcc82a..99b1d6e 100644 --- a/vba/excel-vba/core-concepts/Loop Through Sheets And Books.bas +++ b/vba/vba-excel/workbook/Loop Through Sheets And Books.bas @@ -1,93 +1,93 @@ -Attribute VB_Name = "Module1" -Sub LoopThroughWorksheets_Method1() - - ' -------------------------------------------------------------------------------------------------------------- - 'If I want to declare a collection variable I have to declare it as a "SHEETS" collection object. - 'This is because the "WORKSHEETS" property that is returned from a "WORKBOOK" object is a "SHEETS" - 'collection, not a "WORKSHEETS" collection. A "SHEETS" collection object CONTAINS BOTH WORKSHEET OBJECTS - '& CHART SHEET OBJECTS. - ' -------------------------------------------------------------------------------------------------------------- - - Dim WrkShtCol As Sheets - Dim WrkSht As Worksheet - - Set WrkShtCol = ActiveWorkbook.Worksheets - - For Each WrkSht In WrkShtCol - - WrkSht.Range("A1").Value = WrkSht.Name - - Next WrkSht - -End Sub - -Sub LoopThroughWorksheets_Method2() - - Dim WrkSht As Worksheet - - For Each WrkSht In ActiveWorkbook.Worksheets '<<< THIS IS STILL RETURNING A SHEETS COLLECTION OBJECT - - WrkSht.Range("A1").Value = WrkSht.Name - - Next WrkSht - -End Sub - -Sub LoopThroughWorksheets_Method3() - - ' -------------------------------------------------------------------------------------------------------------- - 'The "THISWORKBOOK" method will only work in the WORKBOOK THAT CONTAINS THE CODE. - 'For example, if I try to run this code while it is in my PERSONAL MACRO WORKBOOK, it will not work. - 'This is because the "THISWORKBOOK" property returns a "WORKBOOK" object that represents the - 'workbook where the CURRENT MACRO CODE IS RUNNING FROM. - ' -------------------------------------------------------------------------------------------------------------- - - Dim WrkSht As Worksheet - - For Each WrkSht In ThisWorkbook.Worksheets - - With WrkSht.Range("A1") - .Value = WrkSht.Name - .Font.Bold = True - End With - - Next WrkSht - -End Sub - -Sub LoopThroughWorksheets_Method4() - - Dim i As Integer - - For i = 1 To ActiveWorkbook.Worksheets.Count - - Worksheets(i).Range("A1").Value = "Hello" - - Next i - -End Sub - - -Sub LoopThroughWorksheets_Method5() - - Dim i As Integer - - For i = ActiveWorkbook.Worksheets.Count To 1 Step -1 - - Worksheets(i).Range("A1").Value = "Hello" - - Next i - -End Sub - -Sub LoopThroughWorksheets_Method6() - - Dim i As Integer - - For i = 1 To ActiveWorkbook.Worksheets.Count Step 2 - - Worksheets(i).Range("A1").Value = "Hello" - - Next i - -End Sub +Attribute VB_Name = "Module1" +Sub LoopThroughWorksheets_Method1() + + ' -------------------------------------------------------------------------------------------------------------- + 'If I want to declare a collection variable I have to declare it as a "SHEETS" collection object. + 'This is because the "WORKSHEETS" property that is returned from a "WORKBOOK" object is a "SHEETS" + 'collection, not a "WORKSHEETS" collection. A "SHEETS" collection object CONTAINS BOTH WORKSHEET OBJECTS + '& CHART SHEET OBJECTS. + ' -------------------------------------------------------------------------------------------------------------- + + Dim WrkShtCol As Sheets + Dim WrkSht As Worksheet + + Set WrkShtCol = ActiveWorkbook.Worksheets + + For Each WrkSht In WrkShtCol + + WrkSht.Range("A1").Value = WrkSht.Name + + Next WrkSht + +End Sub + +Sub LoopThroughWorksheets_Method2() + + Dim WrkSht As Worksheet + + For Each WrkSht In ActiveWorkbook.Worksheets '<<< THIS IS STILL RETURNING A SHEETS COLLECTION OBJECT + + WrkSht.Range("A1").Value = WrkSht.Name + + Next WrkSht + +End Sub + +Sub LoopThroughWorksheets_Method3() + + ' -------------------------------------------------------------------------------------------------------------- + 'The "THISWORKBOOK" method will only work in the WORKBOOK THAT CONTAINS THE CODE. + 'For example, if I try to run this code while it is in my PERSONAL MACRO WORKBOOK, it will not work. + 'This is because the "THISWORKBOOK" property returns a "WORKBOOK" object that represents the + 'workbook where the CURRENT MACRO CODE IS RUNNING FROM. + ' -------------------------------------------------------------------------------------------------------------- + + Dim WrkSht As Worksheet + + For Each WrkSht In ThisWorkbook.Worksheets + + With WrkSht.Range("A1") + .Value = WrkSht.Name + .Font.Bold = True + End With + + Next WrkSht + +End Sub + +Sub LoopThroughWorksheets_Method4() + + Dim i As Integer + + For i = 1 To ActiveWorkbook.Worksheets.Count + + Worksheets(i).Range("A1").Value = "Hello" + + Next i + +End Sub + + +Sub LoopThroughWorksheets_Method5() + + Dim i As Integer + + For i = ActiveWorkbook.Worksheets.Count To 1 Step -1 + + Worksheets(i).Range("A1").Value = "Hello" + + Next i + +End Sub + +Sub LoopThroughWorksheets_Method6() + + Dim i As Integer + + For i = 1 To ActiveWorkbook.Worksheets.Count Step 2 + + Worksheets(i).Range("A1").Value = "Hello" + + Next i + +End Sub diff --git a/vba/excel-vba/core-concepts/Selecting Workbooks.bas b/vba/vba-excel/workbook/Selecting Workbooks.bas similarity index 98% rename from vba/excel-vba/core-concepts/Selecting Workbooks.bas rename to vba/vba-excel/workbook/Selecting Workbooks.bas index 252bd23..6e40820 100644 --- a/vba/excel-vba/core-concepts/Selecting Workbooks.bas +++ b/vba/vba-excel/workbook/Selecting Workbooks.bas @@ -1,87 +1,87 @@ -Sub SelectingWorkbooks() - - ' The application object has a collection that houses all of our workbooks, its called "WORKBOOKS" - ' To access this collection, we call the Application and then the property Workbooks. - ' This collection does not contain add-in workbooks (.xla) and workbooks in protected view are not a member of this collection. - - ' --- "Application.Workbooks" - - ' If we don't use an object qualifier for this property it's equivalent to using "Application.Workbooks" - - ' --- "Workbooks" is the same as "Application.Workbooks" we just are dropping the "Application" object. - - - ' SELECTING INDIVIDUAL WORKBOOKS FROM THE WORKBOOK COLLECTIONS - - ' The Explict way - Using the KEY METHOD - Application.Workbooks("SelectingWorkbooks.xlsx").Activate - Application.Workbooks("SelectingWorkbooks2.xlsx").Activate - ' Workbooks("SelectingWorkbooks.xlsx").Activate <<< Also Works - ' Workbooks("SelectingWorkbooks2.xlsx").Activate <<< Also Works - - ' The Less Explict way - Using the INDEX METHOD. - ' NOTE ONE: Index is determined by the order in which my workbooks were open. - ' NOTE TWO: If you have a PERSONAL.XSLB then this is ALSO a workbook in your collection and it is ALWAYS OPENED FIRST - - Application.Workbooks(1).Activate '<<< This is my Personal Macro Workbook and this workbook is ALWAYS OPENED FIRST - Application.Workbooks(2).Activate '<<< This is my workbook that was opened SECOND and it is named "SelectingWorkbooks.xlsx" - Application.Workbooks(3).Activate '<<< This is my workbook that was opened THIRD and it is named "SelectingWorkbooks2.xlsx" - ' Workbooks(1).Activate '<<< Also Works - ' Workbooks(2).Activate '<<< Also Works - ' Workbooks(3).Activate '<<< Also Works - - - ' Using the ActiveWorkbook Method - ' NOTE ONE: The ActiveWorkbook is the one that is opened and we can see on our screen. - ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 - - ' Using the ThisWorkbook Method - ' NOTE ONE: The ThisWorkbook is the one that houses our code. - ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 - - -End Sub - -Sub SelectingWorkbookMethods() - - ' The application object has a collection that houses all of our workbooks, its called "WORKBOOKS" - ' To access this collection, we call the Application and then the property Workbooks. - ' This collection does not contain add-in workbooks (.xla) and workbooks in protected view are not a member of this collection. - - ' --- "Application.Workbooks" - - ' If we don't use an object qualifier for this property it's equivalent to using "Application.Workbooks" - - ' --- "Workbooks" is the same as "Application.Workbooks" we just are dropping the "Application" object. - - - ' SELECTING INDIVIDUAL WORKBOOKS FROM THE WORKBOOK COLLECTIONS - - ' The Explict way - Using the KEY METHOD - Application.Workbooks("SelectingWorkbooks.xlsx").Activate - Application.Workbooks("SelectingWorkbooks2.xlsx").Activate - ' Workbooks("SelectingWorkbooks.xlsx").Activate <<< Also Works - ' Workbooks("SelectingWorkbooks2.xlsx").Activate <<< Also Works - - ' The Less Explict way - Using the INDEX METHOD. - ' NOTE ONE: Index is determined by the order in which my workbooks were open. - ' NOTE TWO: If you have a PERSONAL.XSLB then this is ALSO a workbook in your collection and it is ALWAYS OPENED FIRST - - Application.Workbooks(1).Activate '<<< This is my Personal Macro Workbook and this workbook is ALWAYS OPENED FIRST - Application.Workbooks(2).Activate '<<< This is my workbook that was opened SECOND and it is named "SelectingWorkbooks.xlsx" - Application.Workbooks(3).Activate '<<< This is my workbook that was opened THIRD and it is named "SelectingWorkbooks2.xlsx" - ' Workbooks(1).Activate '<<< Also Works - ' Workbooks(2).Activate '<<< Also Works - ' Workbooks(3).Activate '<<< Also Works - - - ' Using the ActiveWorkbook Method - ' NOTE ONE: The ActiveWorkbook is the one that is opened and we can see on our screen. - ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 - - ' Using the ThisWorkbook Method - ' NOTE ONE: The ThisWorkbook is the one that houses our code. - ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 - - -End Sub +Sub SelectingWorkbooks() + + ' The application object has a collection that houses all of our workbooks, its called "WORKBOOKS" + ' To access this collection, we call the Application and then the property Workbooks. + ' This collection does not contain add-in workbooks (.xla) and workbooks in protected view are not a member of this collection. + + ' --- "Application.Workbooks" + + ' If we don't use an object qualifier for this property it's equivalent to using "Application.Workbooks" + + ' --- "Workbooks" is the same as "Application.Workbooks" we just are dropping the "Application" object. + + + ' SELECTING INDIVIDUAL WORKBOOKS FROM THE WORKBOOK COLLECTIONS + + ' The Explict way - Using the KEY METHOD + Application.Workbooks("SelectingWorkbooks.xlsx").Activate + Application.Workbooks("SelectingWorkbooks2.xlsx").Activate + ' Workbooks("SelectingWorkbooks.xlsx").Activate <<< Also Works + ' Workbooks("SelectingWorkbooks2.xlsx").Activate <<< Also Works + + ' The Less Explict way - Using the INDEX METHOD. + ' NOTE ONE: Index is determined by the order in which my workbooks were open. + ' NOTE TWO: If you have a PERSONAL.XSLB then this is ALSO a workbook in your collection and it is ALWAYS OPENED FIRST + + Application.Workbooks(1).Activate '<<< This is my Personal Macro Workbook and this workbook is ALWAYS OPENED FIRST + Application.Workbooks(2).Activate '<<< This is my workbook that was opened SECOND and it is named "SelectingWorkbooks.xlsx" + Application.Workbooks(3).Activate '<<< This is my workbook that was opened THIRD and it is named "SelectingWorkbooks2.xlsx" + ' Workbooks(1).Activate '<<< Also Works + ' Workbooks(2).Activate '<<< Also Works + ' Workbooks(3).Activate '<<< Also Works + + + ' Using the ActiveWorkbook Method + ' NOTE ONE: The ActiveWorkbook is the one that is opened and we can see on our screen. + ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 + + ' Using the ThisWorkbook Method + ' NOTE ONE: The ThisWorkbook is the one that houses our code. + ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 + + +End Sub + +Sub SelectingWorkbookMethods() + + ' The application object has a collection that houses all of our workbooks, its called "WORKBOOKS" + ' To access this collection, we call the Application and then the property Workbooks. + ' This collection does not contain add-in workbooks (.xla) and workbooks in protected view are not a member of this collection. + + ' --- "Application.Workbooks" + + ' If we don't use an object qualifier for this property it's equivalent to using "Application.Workbooks" + + ' --- "Workbooks" is the same as "Application.Workbooks" we just are dropping the "Application" object. + + + ' SELECTING INDIVIDUAL WORKBOOKS FROM THE WORKBOOK COLLECTIONS + + ' The Explict way - Using the KEY METHOD + Application.Workbooks("SelectingWorkbooks.xlsx").Activate + Application.Workbooks("SelectingWorkbooks2.xlsx").Activate + ' Workbooks("SelectingWorkbooks.xlsx").Activate <<< Also Works + ' Workbooks("SelectingWorkbooks2.xlsx").Activate <<< Also Works + + ' The Less Explict way - Using the INDEX METHOD. + ' NOTE ONE: Index is determined by the order in which my workbooks were open. + ' NOTE TWO: If you have a PERSONAL.XSLB then this is ALSO a workbook in your collection and it is ALWAYS OPENED FIRST + + Application.Workbooks(1).Activate '<<< This is my Personal Macro Workbook and this workbook is ALWAYS OPENED FIRST + Application.Workbooks(2).Activate '<<< This is my workbook that was opened SECOND and it is named "SelectingWorkbooks.xlsx" + Application.Workbooks(3).Activate '<<< This is my workbook that was opened THIRD and it is named "SelectingWorkbooks2.xlsx" + ' Workbooks(1).Activate '<<< Also Works + ' Workbooks(2).Activate '<<< Also Works + ' Workbooks(3).Activate '<<< Also Works + + + ' Using the ActiveWorkbook Method + ' NOTE ONE: The ActiveWorkbook is the one that is opened and we can see on our screen. + ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 + + ' Using the ThisWorkbook Method + ' NOTE ONE: The ThisWorkbook is the one that houses our code. + ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000 + + +End Sub diff --git a/vba/excel-vba/core-concepts/Selecting Worksheets.bas b/vba/vba-excel/worksheet/Selecting Worksheets.bas similarity index 94% rename from vba/excel-vba/core-concepts/Selecting Worksheets.bas rename to vba/vba-excel/worksheet/Selecting Worksheets.bas index 308ed48..27bbcf6 100644 --- a/vba/excel-vba/core-concepts/Selecting Worksheets.bas +++ b/vba/vba-excel/worksheet/Selecting Worksheets.bas @@ -1,49 +1,49 @@ -Attribute VB_Name = "Module1" -Sub SelectWorkSheet_Method1() - - 'Worksheets Collection - Key Method - - Worksheets("Sheet2").Range("A1").Value = 300 - -End Sub - -Sub SelectWorksheet_Method2() - - 'Worksheets Collection - Index Method - - Worksheets(2).Range("A1").Value = 300 - -End Sub - -Sub SelectWorksheet_Method3() - - 'Sheets Collection - Key Method - - Sheets("Sheet1").Range("A1").Value = 300 - -End Sub - -Sub SelectWorksheet_Method4() - - 'Sheets Collection - Index Method - - Sheets(1).Range("A1").Value = 300 - -End Sub - -Sub SelectWorksheet_Method5() - - 'ActiveSheet Method - - ActiveSheet.Range("A1").Value = 300 - -End Sub - -Sub SelectWorksheet_Method6() - - 'Unqualified Object Name Method (Also Called CodeName Method) - 'WARNING - UNSTABLE WHEN YOU HAVE STORED IN A PERSONAL MACRO WORKBOOK - - Sheet1.Range("A1").Value = 300 - -End Sub +Attribute VB_Name = "Module1" +Sub SelectWorkSheet_Method1() + + 'Worksheets Collection - Key Method + + Worksheets("Sheet2").Range("A1").Value = 300 + +End Sub + +Sub SelectWorksheet_Method2() + + 'Worksheets Collection - Index Method + + Worksheets(2).Range("A1").Value = 300 + +End Sub + +Sub SelectWorksheet_Method3() + + 'Sheets Collection - Key Method + + Sheets("Sheet1").Range("A1").Value = 300 + +End Sub + +Sub SelectWorksheet_Method4() + + 'Sheets Collection - Index Method + + Sheets(1).Range("A1").Value = 300 + +End Sub + +Sub SelectWorksheet_Method5() + + 'ActiveSheet Method + + ActiveSheet.Range("A1").Value = 300 + +End Sub + +Sub SelectWorksheet_Method6() + + 'Unqualified Object Name Method (Also Called CodeName Method) + 'WARNING - UNSTABLE WHEN YOU HAVE STORED IN A PERSONAL MACRO WORKBOOK + + Sheet1.Range("A1").Value = 300 + +End Sub diff --git a/vba/powerpoint-vba/Excel Chart To PowerPoint.bas b/vba/vba-powerpoint/Excel to PowerPoint - Charts.bas similarity index 96% rename from vba/powerpoint-vba/Excel Chart To PowerPoint.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Charts.bas index 9ae3a8b..bb772ed 100644 --- a/vba/powerpoint-vba/Excel Chart To PowerPoint.bas +++ b/vba/vba-powerpoint/Excel to PowerPoint - Charts.bas @@ -1,217 +1,216 @@ -Attribute VB_Name = "Module1" -Sub ExportChartToPowerPoint() - - ' OVERVIEW: - ' This script will create a new PowerPoint Presentation and copy the chart - ' we specify to the newly created PowerPoint Presentation. - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - - 'Dim Excel Variables - Dim Chrt As ChartObject - - 'Create a new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create a new presentation in the PowerPoint Application - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new slide in the PowerPoint Presentation - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) - - 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. - Set Chrt = Worksheets("Charts_One").ChartObjects(1) - - 'Copy the Chart Object variable we specified above. - Chrt.Copy - - 'Paste the Chart Object on the Slide that we created above. - PPTSlide.Shapes.Paste - - -End Sub - -Sub ExportChartsToPowerPoint_SingleWorksheet() - - ' OVERVIEW: - ' This script will loop through all the Charts in the Active worksheet - ' and copy each Chart to a new PowerPoint presentation that we create. - ' Each chart will get their own individual slide and will be placed in the center of it. - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - Dim SldIndex As Integer - - 'Declare Excel Variables - Dim Chrt As ChartObject - - 'Create new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create new presentation in the PowerPoint application. - Set PPTPres = PPTApp.Presentations.Add - - 'Create an index handler for slide creation. - SldIndex = 1 - - 'Loop through all the CHARTOBJECTS in the ACTIVESHEET. - For Each Chrt In ActiveSheet.ChartObjects - - 'Copy the Chart - Chrt.Copy - - 'Create a new slide in the Presentation, set the layout to blank, and paste chart on to the newly added slide. - Set PPTSlide = PPTPres.Slides.Add(SldIndex, ppLayoutBlank) - PPTSlide.Shapes.Paste - - 'Increment index so that way we paste the next chart on the new slide that is added. - SldIndex = SldIndex + 1 - - Next Chrt - - -End Sub - - - -Sub ExportChartsToPowerPoint_MultipleWorksheets() - - ' OVERVIEW: - ' This script will loop through all the worksheets in the Active Workbook - ' and copy all the Charts to a new PowerPoint presentation that we create. - ' Each chart will get their own individual slide and will be placed in the center of it. - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - Dim SldIndex As Integer - - 'Declare Excel Variables - Dim Chrt As ChartObject - Dim WrkSht As Worksheet - - 'Create new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create new presentation in the PowerPoint application. - Set PPTPres = PPTApp.Presentations.Add - - 'Create an index handler for slide creation. - SldIndex = 1 - - 'Loop throught all the Worksheets in the Worksheets Collection. - For Each WrkSht In Worksheets - - 'Loop through all the CHARTOBJECTS in the ACTIVESHEET. - For Each Chrt In WrkSht.ChartObjects - - 'Copy the Chart - Chrt.Copy - - 'Create a new slide in the Presentation, set the layout to blank, and paste chart on to the newly added slide. - Set PPTSlide = PPTPres.Slides.Add(SldIndex, ppLayoutBlank) - PPTSlide.Shapes.Paste - - 'Increment index so that way we paste the next chart on the new slide that is added. - SldIndex = SldIndex + 1 - - Next Chrt - - Next WrkSht - -End Sub - - -Sub ExportChartToPowerPoint_PasteMethods() - - ' OVERVIEW: - ' This script will create a new PowerPoint Presentation and copy the chart - ' we specify to the newly created PowerPoint Presentation. - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - - 'Dim Excel Variables - Dim Chrt As ChartObject - - 'Create a new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create a new presentation in the PowerPoint Application - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new slide in the PowerPoint Presentation - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) - - 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. - Set Chrt = Worksheets("Charts_One").ChartObjects(1) - - 'Copy the Chart. - Chrt.Copy - - 'Copy the Chart Area, use when we want to paste as an OLEObject. - 'Chrt.Chart.ChartArea.Copy - - 'PASTE USING REGULAR PASTE METHOD - - 'Use Paste method to Paste as Chart Object in PowerPoint - 'PPTSlide.Shapes.Paste - - 'PASTE USING PASTESPECIAL METHOD - - 'Paste as Bitmap - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteBitmap - - 'Paste as Default - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteDefault - - 'Paste as EnhancedMetafile - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile - - 'Paste as HTML - DOES NOT WORK WITH CHARTS - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteHTML - - 'Paste as GIF - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteGIF - - 'Paste as JPG - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteJPG - - 'Paste as MetafilePicture - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteMetafilePicture - - 'Paste as PNG - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPastePNG - - 'Paste as Shape - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteShape - - 'Paste as Shape and it is linked. - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteShape, Link:=msoTrue - - 'Paste as Shape, display it as an icon, change the icon label, and make it a linked icon. - 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteShape, DisplayAsIcon:=True, IconLabel:="Link to my Chart", Link:=msoTrue - - 'Paste as OLEObject and it is linked. - PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue - -End Sub - - - +Sub ExportChartToPowerPoint() + + ' OVERVIEW: + ' This script will create a new PowerPoint Presentation and copy the chart + ' we specify to the newly created PowerPoint Presentation. + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + + 'Dim Excel Variables + Dim Chrt As ChartObject + + 'Create a new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create a new presentation in the PowerPoint Application + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new slide in the PowerPoint Presentation + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) + + 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. + Set Chrt = Worksheets("Charts_One").ChartObjects(1) + + 'Copy the Chart Object variable we specified above. + Chrt.Copy + + 'Paste the Chart Object on the Slide that we created above. + PPTSlide.Shapes.Paste + + +End Sub + +Sub ExportChartsToPowerPoint_SingleWorksheet() + + ' OVERVIEW: + ' This script will loop through all the Charts in the Active worksheet + ' and copy each Chart to a new PowerPoint presentation that we create. + ' Each chart will get their own individual slide and will be placed in the center of it. + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + Dim SldIndex As Integer + + 'Declare Excel Variables + Dim Chrt As ChartObject + + 'Create new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create new presentation in the PowerPoint application. + Set PPTPres = PPTApp.Presentations.Add + + 'Create an index handler for slide creation. + SldIndex = 1 + + 'Loop through all the CHARTOBJECTS in the ACTIVESHEET. + For Each Chrt In ActiveSheet.ChartObjects + + 'Copy the Chart + Chrt.Copy + + 'Create a new slide in the Presentation, set the layout to blank, and paste chart on to the newly added slide. + Set PPTSlide = PPTPres.Slides.Add(SldIndex, ppLayoutBlank) + PPTSlide.Shapes.Paste + + 'Increment index so that way we paste the next chart on the new slide that is added. + SldIndex = SldIndex + 1 + + Next Chrt + + +End Sub + + + +Sub ExportChartsToPowerPoint_MultipleWorksheets() + + ' OVERVIEW: + ' This script will loop through all the worksheets in the Active Workbook + ' and copy all the Charts to a new PowerPoint presentation that we create. + ' Each chart will get their own individual slide and will be placed in the center of it. + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + Dim SldIndex As Integer + + 'Declare Excel Variables + Dim Chrt As ChartObject + Dim WrkSht As Worksheet + + 'Create new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create new presentation in the PowerPoint application. + Set PPTPres = PPTApp.Presentations.Add + + 'Create an index handler for slide creation. + SldIndex = 1 + + 'Loop throught all the Worksheets in the Worksheets Collection. + For Each WrkSht In Worksheets + + 'Loop through all the CHARTOBJECTS in the ACTIVESHEET. + For Each Chrt In WrkSht.ChartObjects + + 'Copy the Chart + Chrt.Copy + + 'Create a new slide in the Presentation, set the layout to blank, and paste chart on to the newly added slide. + Set PPTSlide = PPTPres.Slides.Add(SldIndex, ppLayoutBlank) + PPTSlide.Shapes.Paste + + 'Increment index so that way we paste the next chart on the new slide that is added. + SldIndex = SldIndex + 1 + + Next Chrt + + Next WrkSht + +End Sub + + +Sub ExportChartToPowerPoint_PasteMethods() + + ' OVERVIEW: + ' This script will create a new PowerPoint Presentation and copy the chart + ' we specify to the newly created PowerPoint Presentation. + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + + 'Dim Excel Variables + Dim Chrt As ChartObject + + 'Create a new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create a new presentation in the PowerPoint Application + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new slide in the PowerPoint Presentation + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) + + 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. + Set Chrt = Worksheets("Charts_One").ChartObjects(1) + + 'Copy the Chart. + Chrt.Copy + + 'Copy the Chart Area, use when we want to paste as an OLEObject. + 'Chrt.Chart.ChartArea.Copy + + 'PASTE USING REGULAR PASTE METHOD + + 'Use Paste method to Paste as Chart Object in PowerPoint + 'PPTSlide.Shapes.Paste + + 'PASTE USING PASTESPECIAL METHOD + + 'Paste as Bitmap + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteBitmap + + 'Paste as Default + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteDefault + + 'Paste as EnhancedMetafile + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteEnhancedMetafile + + 'Paste as HTML - DOES NOT WORK WITH CHARTS + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteHTML + + 'Paste as GIF + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteGIF + + 'Paste as JPG + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteJPG + + 'Paste as MetafilePicture + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteMetafilePicture + + 'Paste as PNG + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPastePNG + + 'Paste as Shape + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteShape + + 'Paste as Shape and it is linked. + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteShape, Link:=msoTrue + + 'Paste as Shape, display it as an icon, change the icon label, and make it a linked icon. + 'PPTSlide.Shapes.PasteSpecial DataType:=ppPasteShape, DisplayAsIcon:=True, IconLabel:="Link to my Chart", Link:=msoTrue + + 'Paste as OLEObject and it is linked. + PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue + +End Sub + + + diff --git a/vba/powerpoint-vba/Excel to PowerPoint Paste Methods.bas b/vba/vba-powerpoint/Excel to PowerPoint - Paste Methods.bas similarity index 100% rename from vba/powerpoint-vba/Excel to PowerPoint Paste Methods.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Paste Methods.bas diff --git a/vba/powerpoint-vba/Excel Picture To PowerPoint.bas b/vba/vba-powerpoint/Excel to PowerPoint - Pictures.bas similarity index 96% rename from vba/powerpoint-vba/Excel Picture To PowerPoint.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Pictures.bas index 397956b..0ed1c59 100644 --- a/vba/powerpoint-vba/Excel Picture To PowerPoint.bas +++ b/vba/vba-powerpoint/Excel to PowerPoint - Pictures.bas @@ -1,86 +1,86 @@ -Attribute VB_Name = "Module3" -Option Explicit - -Public Sub TestCopyPastePic() - -'Declare PowerPoint Variables -Dim PPTApp As PowerPoint.Application -Dim PPTSlide As PowerPoint.Slide -Dim PPTPres As PowerPoint.Presentation -Dim PPTShape As PowerPoint.Shape - -'Declare Excel Variables -Dim ExcShape As Excel.Shape -Dim WrkSht As Worksheet - - 'Check if PowerPoint is active - On Error Resume Next - Set PPTApp = GetObject(, "PowerPoint.Application") - On Error GoTo 0 - - 'Open PowerPoint if not active - If PPTApp Is Nothing Then - Set PPTApp = New PowerPoint.Application - End If - - 'Display the PowerPoint presentation - PPTApp.Visible = True - - 'Create new presentation in PowerPoint - If PPTApp.Presentations.Count = 0 Then - PPTApp.Presentations.Add - End If - - 'Create a reference to the Active Presentation - Set PPTPres = PPTApp.ActivePresentation - - 'Locate Excel charts to paste into the new PowerPoint presentation - For Each WrkSht In ActiveWorkbook.Worksheets - - 'If the Worksheet is visible then continue on. - If WrkSht.Visible Then - - For Each ExcShape In ActiveSheet.Shapes - - If ExcShape.Type = msoPicture Then - - 'Create a new slide - Set PPTSlide = PPTPres.Slides.Add(PPTPres.Slides.Count + 1, ppLayoutText) - - 'Go to the new slide - PPTApp.ActiveWindow.View.GotoSlide PPTPres.Slides.Count - - 'Copy the Shape - ExcShape.Copy - - 'Paste Shape in the slide. - PPTSlide.Shapes.PasteSpecial DataType:=ppPasteMetafilePicture - Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) - PPTShape.Select - - 'Set the dimensions of the shape. - With PPTApp.ActiveWindow.Selection.ShapeRange - .Left = 25 - .Top = 150 - .Width = 250 - .Left = 500 - End With - - End If - - Next ExcShape - - End If - - Next WrkSht - -'Activate the PowerPoint App -PPTApp.Activate - -'Memory clean up -Set PPTSlide = Nothing -Set PPTApp = Nothing -Set PPTShape = Nothing - -End Sub - +Attribute VB_Name = "Module3" +Option Explicit + +Public Sub TestCopyPastePic() + +'Declare PowerPoint Variables +Dim PPTApp As PowerPoint.Application +Dim PPTSlide As PowerPoint.Slide +Dim PPTPres As PowerPoint.Presentation +Dim PPTShape As PowerPoint.Shape + +'Declare Excel Variables +Dim ExcShape As Excel.Shape +Dim WrkSht As Worksheet + + 'Check if PowerPoint is active + On Error Resume Next + Set PPTApp = GetObject(, "PowerPoint.Application") + On Error GoTo 0 + + 'Open PowerPoint if not active + If PPTApp Is Nothing Then + Set PPTApp = New PowerPoint.Application + End If + + 'Display the PowerPoint presentation + PPTApp.Visible = True + + 'Create new presentation in PowerPoint + If PPTApp.Presentations.Count = 0 Then + PPTApp.Presentations.Add + End If + + 'Create a reference to the Active Presentation + Set PPTPres = PPTApp.ActivePresentation + + 'Locate Excel charts to paste into the new PowerPoint presentation + For Each WrkSht In ActiveWorkbook.Worksheets + + 'If the Worksheet is visible then continue on. + If WrkSht.Visible Then + + For Each ExcShape In ActiveSheet.Shapes + + If ExcShape.Type = msoPicture Then + + 'Create a new slide + Set PPTSlide = PPTPres.Slides.Add(PPTPres.Slides.Count + 1, ppLayoutText) + + 'Go to the new slide + PPTApp.ActiveWindow.View.GotoSlide PPTPres.Slides.Count + + 'Copy the Shape + ExcShape.Copy + + 'Paste Shape in the slide. + PPTSlide.Shapes.PasteSpecial DataType:=ppPasteMetafilePicture + Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) + PPTShape.Select + + 'Set the dimensions of the shape. + With PPTApp.ActiveWindow.Selection.ShapeRange + .Left = 25 + .Top = 150 + .Width = 250 + .Left = 500 + End With + + End If + + Next ExcShape + + End If + + Next WrkSht + +'Activate the PowerPoint App +PPTApp.Activate + +'Memory clean up +Set PPTSlide = Nothing +Set PPTApp = Nothing +Set PPTShape = Nothing + +End Sub + diff --git a/vba/powerpoint-vba/Excel Range To PowerPoint.bas b/vba/vba-powerpoint/Excel to PowerPoint - Ranges.bas similarity index 96% rename from vba/powerpoint-vba/Excel Range To PowerPoint.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Ranges.bas index 0d2ff6b..ddcd3bf 100644 --- a/vba/powerpoint-vba/Excel Range To PowerPoint.bas +++ b/vba/vba-powerpoint/Excel to PowerPoint - Ranges.bas @@ -1,121 +1,121 @@ -Attribute VB_Name = "Module1" -Sub ExportRangeToPowerPoint() - - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - - Dim ExcRng As Range - - 'Create a new instance of PowerPoint - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create a new Presentation - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new Slide - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) - - 'Set a reference to the range - Set ExcRng = Range("A1:C5") - - 'Copy Range - ExcRng.Copy - - 'Paste the range in the slide - PPTSlide.Shapes.Paste - - 'Create another slide - Set PPTSlide = PPTPres.Slides.Add(2, ppLayoutBlank) - - PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue - -End Sub - - -Sub ExportMultipleRangeToPowerPoint_Method1() - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - - 'Declare Excel Variables - Dim ExcRng As Range - Dim RngArray As Variant - Dim ShtArray As Variant - - 'Populate our arrays - RngArray = Array("A1:C5", "A10:C14", "C2:E6", "B2:D6") - ShtArray = Array("One", "One", "Two", "Three") - - 'Create a new instance of PowerPoint - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create a new Presentation - Set PPTPres = PPTApp.Presentations.Add - - 'Loop through the range array, create a slide for each range, and copy that range on to the slide. - For x = LBound(RngArray) To UBound(RngArray) - - 'Set a reference to the range - Set ExcRng = Worksheets(ShtArray(x)).Range(RngArray(x)) - - 'Copy the range - ExcRng.Copy - - 'Create a new Slide - Set PPTSlide = PPTPres.Slides.Add(x + 1, ppLayoutBlank) - - 'Paste the range in the slide - PPTSlide.Shapes.Paste - - Next x - -End Sub - - -Sub ExportMultipleRangeToPowerPoint_Method2() - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - - 'Declare Excel Variables - Dim ExcRng As Range - Dim RngArray As Variant - - 'Populate our array - RngArray = Array(Sheet1.Range("A1:C5"), Sheet1.Range("A10:C14"), Sheet2.Range("C2:E6"), Sheet3.Range("B2:D6")) - - 'Create a new instance of PowerPoint - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - - 'Create a new Presentation - Set PPTPres = PPTApp.Presentations.Add - - 'Loop through the range array, create a slide for each range, and copy that range on to the slide. - For x = LBound(RngArray) To UBound(RngArray) - - 'Set a reference to the range - Set ExcRng = RngArray(x) - - 'Copy Range - ExcRng.Copy - - 'Enable this line of code if you recieve error about the range not being in the clipboard - This will fix that error by pausing the program for ONE Second. - 'Application.Wait Now + #12:00:01 AM# - - 'Create a new Slide - Set PPTSlide = PPTPres.Slides.Add(x + 1, ppLayoutBlank) - - 'Paste the range in the slide as a linked OLEObject - PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue - - Next x - -End Sub +Attribute VB_Name = "Module1" +Sub ExportRangeToPowerPoint() + + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + + Dim ExcRng As Range + + 'Create a new instance of PowerPoint + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create a new Presentation + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new Slide + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) + + 'Set a reference to the range + Set ExcRng = Range("A1:C5") + + 'Copy Range + ExcRng.Copy + + 'Paste the range in the slide + PPTSlide.Shapes.Paste + + 'Create another slide + Set PPTSlide = PPTPres.Slides.Add(2, ppLayoutBlank) + + PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue + +End Sub + + +Sub ExportMultipleRangeToPowerPoint_Method1() + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + + 'Declare Excel Variables + Dim ExcRng As Range + Dim RngArray As Variant + Dim ShtArray As Variant + + 'Populate our arrays + RngArray = Array("A1:C5", "A10:C14", "C2:E6", "B2:D6") + ShtArray = Array("One", "One", "Two", "Three") + + 'Create a new instance of PowerPoint + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create a new Presentation + Set PPTPres = PPTApp.Presentations.Add + + 'Loop through the range array, create a slide for each range, and copy that range on to the slide. + For x = LBound(RngArray) To UBound(RngArray) + + 'Set a reference to the range + Set ExcRng = Worksheets(ShtArray(x)).Range(RngArray(x)) + + 'Copy the range + ExcRng.Copy + + 'Create a new Slide + Set PPTSlide = PPTPres.Slides.Add(x + 1, ppLayoutBlank) + + 'Paste the range in the slide + PPTSlide.Shapes.Paste + + Next x + +End Sub + + +Sub ExportMultipleRangeToPowerPoint_Method2() + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + + 'Declare Excel Variables + Dim ExcRng As Range + Dim RngArray As Variant + + 'Populate our array + RngArray = Array(Sheet1.Range("A1:C5"), Sheet1.Range("A10:C14"), Sheet2.Range("C2:E6"), Sheet3.Range("B2:D6")) + + 'Create a new instance of PowerPoint + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + + 'Create a new Presentation + Set PPTPres = PPTApp.Presentations.Add + + 'Loop through the range array, create a slide for each range, and copy that range on to the slide. + For x = LBound(RngArray) To UBound(RngArray) + + 'Set a reference to the range + Set ExcRng = RngArray(x) + + 'Copy Range + ExcRng.Copy + + 'Enable this line of code if you recieve error about the range not being in the clipboard - This will fix that error by pausing the program for ONE Second. + 'Application.Wait Now + #12:00:01 AM# + + 'Create a new Slide + Set PPTSlide = PPTPres.Slides.Add(x + 1, ppLayoutBlank) + + 'Paste the range in the slide as a linked OLEObject + PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject, Link:=msoTrue + + Next x + +End Sub diff --git a/vba/powerpoint-vba/Excel Shape Manipulation In PowerPoint.bas b/vba/vba-powerpoint/Excel to PowerPoint - Shape Manipulation.bas similarity index 96% rename from vba/powerpoint-vba/Excel Shape Manipulation In PowerPoint.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Shape Manipulation.bas index 43eacda..6a8fb35 100644 --- a/vba/powerpoint-vba/Excel Shape Manipulation In PowerPoint.bas +++ b/vba/vba-powerpoint/Excel to PowerPoint - Shape Manipulation.bas @@ -1,210 +1,210 @@ -Attribute VB_Name = "Module1" -Sub ManipulateShapeInPowerPoint() - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - - 'Dim Excel Variables - Dim Chrt As ChartObject - - 'Create a new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - PPTApp.Activate - - 'Create a new presentation in the PowerPoint Application - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new slide in the PowerPoint Presentation - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) - - 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. - Set Chrt = Worksheets("Object").ChartObjects(1) - - 'Copy the Chart Object variable we specified above. - Chrt.Copy - - 'Paste the Chart Object on the Slide that we created above. - PPTSlide.Shapes.Paste - - 'Set a reference to the shape we want to manipulate - Set PPTShape = PPTSlide.Shapes(2) - 'Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) - - 'Set the height, width, top & left of the shape - With PPTShape - .Left = 100 - .Top = 100 - .Height = 300 - .Width = 300 - End With - -End Sub - - -Sub AligningShapesInPowerPointAlign_MethodOne() - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - - 'Dim Excel Variables - Dim Chrt As ChartObject - - 'Create a new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - PPTApp.Activate - - 'Create a new presentation in the PowerPoint Application - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new slide in the PowerPoint Presentation - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) - - 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. - Set Chrt = Worksheets("Object").ChartObjects(1) - - 'Copy the Chart Object variable we specified above. - Chrt.Copy - - 'Paste the Chart Object on the Slide that we created above. - PPTSlide.Shapes.Paste - - 'Set a reference to the shape we want to manipulate - Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) - - 'Set the height & width of the shape - With PPTShape - .Height = 300 - .Width = 300 - End With - - 'Get the Slide Width & Slide Height - SldHeight = PPTPres.PageSetup.SlideHeight - SldWidth = PPTPres.PageSetup.SlideWidth - - 'Calculate the Slide Center and Slide Middle - SldMiddle = (SldHeight / 2) - SldCenter = (SldWidth / 2) - - 'Calculate Shape Center and Shape Middle - ShpMiddle = (PPTShape.Height / 2) - ShpCenter = (PPTShape.Width / 2) - - 'Center the shape and align it to the middle - With PPTShape - .Left = SldCenter - ShpCenter - .Top = SldMiddle - ShpMiddle - End With - - -End Sub - - - -Sub AligningShapesInPowerPointAlign_MethodTwo() - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - Dim PPTShapeRng As PowerPoint.ShapeRange - Dim ShpCount As Integer - - 'Dim Excel Variables - Dim Chrt As ChartObject - - 'Create a new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - PPTApp.Activate - - 'Create a new presentation in the PowerPoint Application - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new slide in the PowerPoint Presentation - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) - - 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. - Set Chrt = Worksheets("Object").ChartObjects(1) - - 'Copy the Chart Object variable we specified above. - Chrt.Copy - - 'Paste the Chart Object on the Slide that we created above. - PPTSlide.Shapes.Paste - - 'Count Shapes on Slide - ShpCount = PPTSlide.Shapes.Count - - 'Create a reference to a shape range that will contain multiple shapes. - Set PPTShapeRng = PPTSlide.Shapes.Range(Array(ShpCount)) - - 'Set the height & width of the shape. - With PPTShapeRng - .Height = 300 - .Width = 300 - End With - - 'Align Shape to the middle & center of the SLIDE - PPTShapeRng.Align msoAlignCenters, True - PPTShapeRng.Align msoAlignMiddles, True - -End Sub - - -Sub AligningShapesInPowerPointAlign_MethodThree() - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - - 'Dim Excel Variables - Dim Chrt As ChartObject - - 'Create a new PowerPoint Application & make it visible. - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - PPTApp.Activate - - 'Create a new presentation in the PowerPoint Application - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new slide in the PowerPoint Presentation - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) - - 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. - Set Chrt = Worksheets("Object").ChartObjects(1) - - 'Copy the Chart Object variable we specified above. - Chrt.Copy - - 'Paste the Chart Object on the Slide that we created above & select that shape - PPTSlide.Shapes.Paste.Select - - 'Set dimensions of the shape - With PPTApp.ActiveWindow.Selection.ShapeRange - - .Height = 300 - .Width = 300 - .Align msoAlignMiddles, True - .Align msoAlignCenters, True - - End With - - -End Sub - - - - - - +Attribute VB_Name = "Module1" +Sub ManipulateShapeInPowerPoint() + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + + 'Dim Excel Variables + Dim Chrt As ChartObject + + 'Create a new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + PPTApp.Activate + + 'Create a new presentation in the PowerPoint Application + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new slide in the PowerPoint Presentation + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) + + 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. + Set Chrt = Worksheets("Object").ChartObjects(1) + + 'Copy the Chart Object variable we specified above. + Chrt.Copy + + 'Paste the Chart Object on the Slide that we created above. + PPTSlide.Shapes.Paste + + 'Set a reference to the shape we want to manipulate + Set PPTShape = PPTSlide.Shapes(2) + 'Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) + + 'Set the height, width, top & left of the shape + With PPTShape + .Left = 100 + .Top = 100 + .Height = 300 + .Width = 300 + End With + +End Sub + + +Sub AligningShapesInPowerPointAlign_MethodOne() + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + + 'Dim Excel Variables + Dim Chrt As ChartObject + + 'Create a new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + PPTApp.Activate + + 'Create a new presentation in the PowerPoint Application + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new slide in the PowerPoint Presentation + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) + + 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. + Set Chrt = Worksheets("Object").ChartObjects(1) + + 'Copy the Chart Object variable we specified above. + Chrt.Copy + + 'Paste the Chart Object on the Slide that we created above. + PPTSlide.Shapes.Paste + + 'Set a reference to the shape we want to manipulate + Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) + + 'Set the height & width of the shape + With PPTShape + .Height = 300 + .Width = 300 + End With + + 'Get the Slide Width & Slide Height + SldHeight = PPTPres.PageSetup.SlideHeight + SldWidth = PPTPres.PageSetup.SlideWidth + + 'Calculate the Slide Center and Slide Middle + SldMiddle = (SldHeight / 2) + SldCenter = (SldWidth / 2) + + 'Calculate Shape Center and Shape Middle + ShpMiddle = (PPTShape.Height / 2) + ShpCenter = (PPTShape.Width / 2) + + 'Center the shape and align it to the middle + With PPTShape + .Left = SldCenter - ShpCenter + .Top = SldMiddle - ShpMiddle + End With + + +End Sub + + + +Sub AligningShapesInPowerPointAlign_MethodTwo() + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + Dim PPTShapeRng As PowerPoint.ShapeRange + Dim ShpCount As Integer + + 'Dim Excel Variables + Dim Chrt As ChartObject + + 'Create a new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + PPTApp.Activate + + 'Create a new presentation in the PowerPoint Application + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new slide in the PowerPoint Presentation + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) + + 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. + Set Chrt = Worksheets("Object").ChartObjects(1) + + 'Copy the Chart Object variable we specified above. + Chrt.Copy + + 'Paste the Chart Object on the Slide that we created above. + PPTSlide.Shapes.Paste + + 'Count Shapes on Slide + ShpCount = PPTSlide.Shapes.Count + + 'Create a reference to a shape range that will contain multiple shapes. + Set PPTShapeRng = PPTSlide.Shapes.Range(Array(ShpCount)) + + 'Set the height & width of the shape. + With PPTShapeRng + .Height = 300 + .Width = 300 + End With + + 'Align Shape to the middle & center of the SLIDE + PPTShapeRng.Align msoAlignCenters, True + PPTShapeRng.Align msoAlignMiddles, True + +End Sub + + +Sub AligningShapesInPowerPointAlign_MethodThree() + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + + 'Dim Excel Variables + Dim Chrt As ChartObject + + 'Create a new PowerPoint Application & make it visible. + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + PPTApp.Activate + + 'Create a new presentation in the PowerPoint Application + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new slide in the PowerPoint Presentation + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutTitleOnly) + + 'Create a Chart Object variable where specify the sheet the chart is on and the index number of that chart. + Set Chrt = Worksheets("Object").ChartObjects(1) + + 'Copy the Chart Object variable we specified above. + Chrt.Copy + + 'Paste the Chart Object on the Slide that we created above & select that shape + PPTSlide.Shapes.Paste.Select + + 'Set dimensions of the shape + With PPTApp.ActiveWindow.Selection.ShapeRange + + .Height = 300 + .Width = 300 + .Align msoAlignMiddles, True + .Align msoAlignCenters, True + + End With + + +End Sub + + + + + + diff --git a/vba/powerpoint-vba/Multiple Excel Objects To PowerPoint.bas b/vba/vba-powerpoint/Excel to PowerPoint - Specific Slide Multiple Objects.bas similarity index 96% rename from vba/powerpoint-vba/Multiple Excel Objects To PowerPoint.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Specific Slide Multiple Objects.bas index 53ac21e..d41b524 100644 --- a/vba/powerpoint-vba/Multiple Excel Objects To PowerPoint.bas +++ b/vba/vba-powerpoint/Excel to PowerPoint - Specific Slide Multiple Objects.bas @@ -1,87 +1,87 @@ -Attribute VB_Name = "Module2" -Option Explicit - -Sub CopyMultiObjectsToPPT() - - 'Declare PowerPoint Variables - Dim PPTApp As PowerPoint.Application - Dim PPTPres As PowerPoint.Presentation - Dim PPTSlide As PowerPoint.Slide - Dim PPTShape As PowerPoint.Shape - - 'Declare Excel Variables - Dim ExcObj, ObjType, ObjArray As Variant - Dim LefArray, TopArray, HgtArray, WidArray As Variant - Dim x As Integer - - 'Create a new instance of PowerPoint - Set PPTApp = New PowerPoint.Application - PPTApp.Visible = True - PPTApp.Activate - - 'Create a new presentation - Set PPTPres = PPTApp.Presentations.Add - - 'Create a new slide in the presentation - Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) - - 'Create array to house objects we want to export - ObjArray = Array(Sheet2.Range("B2:D5"), Sheet2.ChartObjects(1), Sheet2.ListObjects(1)) - - 'Define my dimension arrays - LefArray = Array(59.3, 59.3, 451.5) - TopArray = Array(270, 34.44, 34.44) - HgtArray = Array(105.27, 215.25, 131.64) - WidArray = Array(359.23, 359.25, 449.22) - - 'Loop through the object array and copy each object - For x = LBound(ObjArray) To UBound(ObjArray) - - 'Determine Object Type - ObjType = TypeName(ObjArray(x)) - - 'Depending on the object type, copy it a certain way - Select Case ObjType - - Case "Range" - Set ExcObj = ObjArray(x) - ExcObj.Copy - - Case "ChartObject" - Set ExcObj = ObjArray(x) - ExcObj.Chart.ChartArea.Copy - - Case "ListObject" - Set ExcObj = ObjArray(x) - ExcObj.Range.Copy - - End Select - - 'Pause the Excel Application - Application.Wait Now() + #12:00:01 AM# - - 'Paste the object in the slide - PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject - - 'Set a reference to the shape - Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) - - 'Set the dimension of my shape - With PPTShape - .Left = LefArray(x) - .Height = HgtArray(x) - .Width = WidArray(x) - .Top = TopArray(x) - End With - - Next - -End Sub - - - - - - - - +Attribute VB_Name = "Module2" +Option Explicit + +Sub CopyMultiObjectsToPPT() + + 'Declare PowerPoint Variables + Dim PPTApp As PowerPoint.Application + Dim PPTPres As PowerPoint.Presentation + Dim PPTSlide As PowerPoint.Slide + Dim PPTShape As PowerPoint.Shape + + 'Declare Excel Variables + Dim ExcObj, ObjType, ObjArray As Variant + Dim LefArray, TopArray, HgtArray, WidArray As Variant + Dim x As Integer + + 'Create a new instance of PowerPoint + Set PPTApp = New PowerPoint.Application + PPTApp.Visible = True + PPTApp.Activate + + 'Create a new presentation + Set PPTPres = PPTApp.Presentations.Add + + 'Create a new slide in the presentation + Set PPTSlide = PPTPres.Slides.Add(1, ppLayoutBlank) + + 'Create array to house objects we want to export + ObjArray = Array(Sheet2.Range("B2:D5"), Sheet2.ChartObjects(1), Sheet2.ListObjects(1)) + + 'Define my dimension arrays + LefArray = Array(59.3, 59.3, 451.5) + TopArray = Array(270, 34.44, 34.44) + HgtArray = Array(105.27, 215.25, 131.64) + WidArray = Array(359.23, 359.25, 449.22) + + 'Loop through the object array and copy each object + For x = LBound(ObjArray) To UBound(ObjArray) + + 'Determine Object Type + ObjType = TypeName(ObjArray(x)) + + 'Depending on the object type, copy it a certain way + Select Case ObjType + + Case "Range" + Set ExcObj = ObjArray(x) + ExcObj.Copy + + Case "ChartObject" + Set ExcObj = ObjArray(x) + ExcObj.Chart.ChartArea.Copy + + Case "ListObject" + Set ExcObj = ObjArray(x) + ExcObj.Range.Copy + + End Select + + 'Pause the Excel Application + Application.Wait Now() + #12:00:01 AM# + + 'Paste the object in the slide + PPTSlide.Shapes.PasteSpecial DataType:=ppPasteOLEObject + + 'Set a reference to the shape + Set PPTShape = PPTSlide.Shapes(PPTSlide.Shapes.Count) + + 'Set the dimension of my shape + With PPTShape + .Left = LefArray(x) + .Height = HgtArray(x) + .Width = WidArray(x) + .Top = TopArray(x) + End With + + Next + +End Sub + + + + + + + + diff --git a/vba/powerpoint-vba/Export Excel Objects To Specific Slide.bas b/vba/vba-powerpoint/Excel to PowerPoint - Specific Slide.bas similarity index 100% rename from vba/powerpoint-vba/Export Excel Objects To Specific Slide.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Specific Slide.bas diff --git a/vba/powerpoint-vba/Excel Table to PowerPoint.bas b/vba/vba-powerpoint/Excel to PowerPoint - Tables.bas similarity index 100% rename from vba/powerpoint-vba/Excel Table to PowerPoint.bas rename to vba/vba-powerpoint/Excel to PowerPoint - Tables.bas diff --git a/vba/powerpoint-vba/ShapeFinder.bas b/vba/vba-powerpoint/PowerPoint - Copy and Paste Shape Size.bas similarity index 100% rename from vba/powerpoint-vba/ShapeFinder.bas rename to vba/vba-powerpoint/PowerPoint - Copy and Paste Shape Size.bas diff --git a/vba/powerpoint-vba/Working With Slides.bas b/vba/vba-powerpoint/PowerPoint - Slide Object.bas similarity index 100% rename from vba/powerpoint-vba/Working With Slides.bas rename to vba/vba-powerpoint/PowerPoint - Slide Object.bas diff --git a/vba/powerpoint-vba/Working With Text Frames And Text Ranges.bas b/vba/vba-powerpoint/PowerPoint - TextFrame and TextRange Object.bas similarity index 100% rename from vba/powerpoint-vba/Working With Text Frames And Text Ranges.bas rename to vba/vba-powerpoint/PowerPoint - TextFrame and TextRange Object.bas diff --git a/vba/powerpoint-vba/UpdateLinks.bas b/vba/vba-powerpoint/PowerPoint - Update Links.bas similarity index 100% rename from vba/powerpoint-vba/UpdateLinks.bas rename to vba/vba-powerpoint/PowerPoint - Update Links.bas diff --git a/vba/word-vba/Excel Chart To Word.bas b/vba/vba-word/Excel To Word - Chart.bas similarity index 96% rename from vba/word-vba/Excel Chart To Word.bas rename to vba/vba-word/Excel To Word - Chart.bas index 34fcdc7..7840f78 100644 --- a/vba/word-vba/Excel Chart To Word.bas +++ b/vba/vba-word/Excel To Word - Chart.bas @@ -1,167 +1,167 @@ -Attribute VB_Name = "Module1" -Option Explicit - -Sub ExportChartToWord() - - 'Declare Word Object Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - - 'Declare Excel Object Variables - Dim Chrt As ChartObject - - 'Create a New Instance Of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new Word Document - Set WrdDoc = WrdApp.Documents.Add - - 'Create a Reference to the chart I want to Export - Set Chrt = ActiveSheet.ChartObjects(1) - Chrt.Chart.ChartArea.Copy - - 'Paste into Word Document - With WrdApp.Selection - .PasteSpecial Link:=True, DataType:=wdPasteOLEObject - End With - -End Sub - -Sub ExportingToWord_MultipleCharts_Worksheet() - - 'Declare Word Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - Dim SecCnt As Integer - - 'Declare Excel Variables - Dim ChrtObj As ChartObject - Dim Rng As Range - - 'Create a new instance of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new word document - Set WrdDoc = WrdApp.Documents.Add - - 'Loop through the charts on the active sheet - For Each ChrtObj In ActiveSheet.ChartObjects - - 'Copy the chart - ChrtObj.Chart.ChartArea.Copy - - 'Paste the Chart in the Word Document - With WrdApp.Selection - .PasteSpecial Link:=True, DataType:=wdPasteOLEObject, Placement:=wdInLine - End With - - 'Count the pages in the Word Document - SecCnt = WrdApp.ActiveDocument.Sections.Count - - 'Add a new page to the document. - WrdApp.ActiveDocument.Sections.Add - - 'Go to the newly created page. - WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext - - Next ChrtObj - -End Sub - - -Sub ExportingToWord_MultipleCharts_Workbook() - - 'Declare Word Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - Dim SecCnt As Integer - - 'Declare Excel Variables - Dim ChrtObj As ChartObject - Dim WrkSht As Worksheet - Dim Rng As Range - Dim ChrCnt As Integer - - 'Create a new instance of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new word document - Set WrdDoc = WrdApp.Documents.Add - - ChrCnt = 0 - - 'Loop through all the worksheets in the Workbook that contains this code. - For Each WrkSht In ThisWorkbook.Worksheets - - 'Fix the instability error - WrkSht.Activate - - 'Loop through the charts on the active sheet - For Each ChrtObj In WrkSht.ChartObjects - - 'Copy the chart - ChrtObj.Chart.ChartArea.Copy - - 'Increment Chart Count - ChrCnt = ChrCnt + 1 - - 'Fix the instability error - Application.Wait Now + #12:00:01 AM# - - 'Paste the Chart in the Word Document - With WrdApp.Selection - .PasteSpecial Link:=True, DataType:=wdPasteOLEObject, Placement:=wdInLine - End With - - 'Count the pages in the Word Document - SecCnt = WrdApp.ActiveDocument.Sections.Count - - 'Add a new page to the document. - WrdApp.ActiveDocument.Sections.Add - - 'Go to the newly created page. - WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext - - 'Fix instability Errors - Application.CutCopyMode = False - - Next ChrtObj - - Next WrkSht - -End Sub - -Sub ExportChartToWord2() - - 'Declare Word Object Variables - Dim WrdApp As Object - Dim WrdDoc As Object - - 'Declare Excel Object Variables - Dim Chrt As ChartObject - - 'Create a New Instance Of Word - Set WrdApp = CreateObject("Word.Application") - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new Word Document - Set WrdDoc = WrdApp.Documents.Add - - 'Create a Reference to the chart I want to Export - Set Chrt = ActiveSheet.ChartObjects(1) - Chrt.Chart.ChartArea.Copy - - 'Paste into Word Document - With WrdApp.Selection - .PasteSpecial Link:=True, DataType:=wdPasteOLEObject - End With - -End Sub - +Attribute VB_Name = "Module1" +Option Explicit + +Sub ExportChartToWord() + + 'Declare Word Object Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + + 'Declare Excel Object Variables + Dim Chrt As ChartObject + + 'Create a New Instance Of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new Word Document + Set WrdDoc = WrdApp.Documents.Add + + 'Create a Reference to the chart I want to Export + Set Chrt = ActiveSheet.ChartObjects(1) + Chrt.Chart.ChartArea.Copy + + 'Paste into Word Document + With WrdApp.Selection + .PasteSpecial Link:=True, DataType:=wdPasteOLEObject + End With + +End Sub + +Sub ExportingToWord_MultipleCharts_Worksheet() + + 'Declare Word Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + Dim SecCnt As Integer + + 'Declare Excel Variables + Dim ChrtObj As ChartObject + Dim Rng As Range + + 'Create a new instance of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new word document + Set WrdDoc = WrdApp.Documents.Add + + 'Loop through the charts on the active sheet + For Each ChrtObj In ActiveSheet.ChartObjects + + 'Copy the chart + ChrtObj.Chart.ChartArea.Copy + + 'Paste the Chart in the Word Document + With WrdApp.Selection + .PasteSpecial Link:=True, DataType:=wdPasteOLEObject, Placement:=wdInLine + End With + + 'Count the pages in the Word Document + SecCnt = WrdApp.ActiveDocument.Sections.Count + + 'Add a new page to the document. + WrdApp.ActiveDocument.Sections.Add + + 'Go to the newly created page. + WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext + + Next ChrtObj + +End Sub + + +Sub ExportingToWord_MultipleCharts_Workbook() + + 'Declare Word Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + Dim SecCnt As Integer + + 'Declare Excel Variables + Dim ChrtObj As ChartObject + Dim WrkSht As Worksheet + Dim Rng As Range + Dim ChrCnt As Integer + + 'Create a new instance of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new word document + Set WrdDoc = WrdApp.Documents.Add + + ChrCnt = 0 + + 'Loop through all the worksheets in the Workbook that contains this code. + For Each WrkSht In ThisWorkbook.Worksheets + + 'Fix the instability error + WrkSht.Activate + + 'Loop through the charts on the active sheet + For Each ChrtObj In WrkSht.ChartObjects + + 'Copy the chart + ChrtObj.Chart.ChartArea.Copy + + 'Increment Chart Count + ChrCnt = ChrCnt + 1 + + 'Fix the instability error + Application.Wait Now + #12:00:01 AM# + + 'Paste the Chart in the Word Document + With WrdApp.Selection + .PasteSpecial Link:=True, DataType:=wdPasteOLEObject, Placement:=wdInLine + End With + + 'Count the pages in the Word Document + SecCnt = WrdApp.ActiveDocument.Sections.Count + + 'Add a new page to the document. + WrdApp.ActiveDocument.Sections.Add + + 'Go to the newly created page. + WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext + + 'Fix instability Errors + Application.CutCopyMode = False + + Next ChrtObj + + Next WrkSht + +End Sub + +Sub ExportChartToWord2() + + 'Declare Word Object Variables + Dim WrdApp As Object + Dim WrdDoc As Object + + 'Declare Excel Object Variables + Dim Chrt As ChartObject + + 'Create a New Instance Of Word + Set WrdApp = CreateObject("Word.Application") + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new Word Document + Set WrdDoc = WrdApp.Documents.Add + + 'Create a Reference to the chart I want to Export + Set Chrt = ActiveSheet.ChartObjects(1) + Chrt.Chart.ChartArea.Copy + + 'Paste into Word Document + With WrdApp.Selection + .PasteSpecial Link:=True, DataType:=wdPasteOLEObject + End With + +End Sub + diff --git a/vba/word-vba/Excel Range To Word.bas b/vba/vba-word/Excel To Word - Range.bas similarity index 96% rename from vba/word-vba/Excel Range To Word.bas rename to vba/vba-word/Excel To Word - Range.bas index 26d345e..ebf5ed1 100644 --- a/vba/word-vba/Excel Range To Word.bas +++ b/vba/vba-word/Excel To Word - Range.bas @@ -1,91 +1,91 @@ -Attribute VB_Name = "Practice" -Option Explicit - -Sub RangeToWord_Single() - - 'Declare Word Object Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - - 'Declare Excel Object Variable - Dim ExcRng As Range - - 'Create a new instance of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new word document - Set WrdDoc = WrdApp.Documents.Add - - 'Set the Range - Set ExcRng = ActiveSheet.Range("B2:E6") - - 'Copy the range - ExcRng.Copy - - 'Pause the application for two seconds - Application.Wait Now + #12:00:02 AM# - - 'Paste the chart in the Word Document - WrdDoc.Paragraphs(1).Range.PasteExcelTable LinkedToExcel:=True, WordFormatting:=False, RTF:=False - - 'Clear Clipboard - Application.CutCopyMode = False - -End Sub - -Sub RangeToWord_Multi() - - 'Declare Word Object Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - - 'Declare Excel Object Variable - Dim Rng As Variant - Dim ExcRng As Range - Dim RngArray As Variant - - 'Create a new instance of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Array that houses all of our ranges that we want to export - RngArray = Array(Worksheets("Sheet1").Range("B2:E6"), Worksheets("Sheet1").Range("B7:E10"), Worksheets("Sheet2").Range("B2:E5")) - - 'Create a new word document - Set WrdDoc = WrdApp.Documents.Add - - 'Loop through the Charts on my ACTIVE SHEET - For Each Rng In RngArray - - 'Set the Range - Set ExcRng = Rng - - 'Copy the range - Rng.Copy - - 'Pause the application for two seconds - Application.Wait Now + #12:00:02 AM# - - 'Paste the chart in the Word Document - With WrdApp.Selection - .PasteSpecial Link:=True, DataType:=wdPasteOLEObject - End With - - 'Add a new page - WrdApp.ActiveDocument.Sections.Add - - 'Go to the newly created page - WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext - - 'Clear Clipboard - Application.CutCopyMode = False - - Next Rng - -End Sub - - - +Attribute VB_Name = "Practice" +Option Explicit + +Sub RangeToWord_Single() + + 'Declare Word Object Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + + 'Declare Excel Object Variable + Dim ExcRng As Range + + 'Create a new instance of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new word document + Set WrdDoc = WrdApp.Documents.Add + + 'Set the Range + Set ExcRng = ActiveSheet.Range("B2:E6") + + 'Copy the range + ExcRng.Copy + + 'Pause the application for two seconds + Application.Wait Now + #12:00:02 AM# + + 'Paste the chart in the Word Document + WrdDoc.Paragraphs(1).Range.PasteExcelTable LinkedToExcel:=True, WordFormatting:=False, RTF:=False + + 'Clear Clipboard + Application.CutCopyMode = False + +End Sub + +Sub RangeToWord_Multi() + + 'Declare Word Object Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + + 'Declare Excel Object Variable + Dim Rng As Variant + Dim ExcRng As Range + Dim RngArray As Variant + + 'Create a new instance of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Array that houses all of our ranges that we want to export + RngArray = Array(Worksheets("Sheet1").Range("B2:E6"), Worksheets("Sheet1").Range("B7:E10"), Worksheets("Sheet2").Range("B2:E5")) + + 'Create a new word document + Set WrdDoc = WrdApp.Documents.Add + + 'Loop through the Charts on my ACTIVE SHEET + For Each Rng In RngArray + + 'Set the Range + Set ExcRng = Rng + + 'Copy the range + Rng.Copy + + 'Pause the application for two seconds + Application.Wait Now + #12:00:02 AM# + + 'Paste the chart in the Word Document + With WrdApp.Selection + .PasteSpecial Link:=True, DataType:=wdPasteOLEObject + End With + + 'Add a new page + WrdApp.ActiveDocument.Sections.Add + + 'Go to the newly created page + WrdApp.Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext + + 'Clear Clipboard + Application.CutCopyMode = False + + Next Rng + +End Sub + + + diff --git a/vba/word-vba/Excel Table To Word.bas b/vba/vba-word/Excel To Word - Table.bas similarity index 96% rename from vba/word-vba/Excel Table To Word.bas rename to vba/vba-word/Excel To Word - Table.bas index 04917b3..8b482ad 100644 --- a/vba/word-vba/Excel Table To Word.bas +++ b/vba/vba-word/Excel To Word - Table.bas @@ -1,108 +1,108 @@ -Option Explicit - -Sub CopyTableToWord_Single() - - 'Declare Word Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - Dim WrdTbl As Word.Table - - 'Declare Excel Variables - Dim ExcLisObj As ListObject - - 'Create a new instance of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new document in my application - Set WrdDoc = WrdApp.Documents.Add - - 'Define ListObject - Set ExcLisObj = ActiveSheet.ListObjects(1) - - 'Create a reference to the range I want to Copy. - ExcLisObj.Range.Copy - - 'Pause the Excel Application for 2 seconds - Application.Wait Now() + #12:00:01 AM# - - - With WrdApp.Selection - .PasteExcelTable LinkedToExcel:=True, WordFormatting:=True, RTF:=True - End With - - Set WrdTbl = WrdDoc.Tables(WrdDoc.Tables.Count) - WrdTbl.AllowAutoFit = True - WrdTbl.AutoFitBehavior (wdAutoFitWindow) - WrdTbl.Spacing = 19 - WrdTbl.Shading.BackgroundPatternColorIndex = wdBlue - - - 'Create a new page - WrdApp.ActiveDocument.Sections.Add - - 'Go to the newly created page - WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToNext - - 'Clear my clipboard - Application.CutCopyMode = False - - - WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToFirst - -End Sub - -Sub CopyTableToWord_Multi() - - 'Declare Word Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - Dim WrdTbl As Word.Table - - 'Declare Excel Variables - Dim ExcLisObj As ListObject - - 'Create a new instance of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new document in my application - Set WrdDoc = WrdApp.Documents.Add - - 'Loop through each element in the range array - For Each ExcLisObj In ActiveSheet.ListObjects - - 'Create a reference to the range I want to Copy. - ExcLisObj.Range.Copy - - 'Pause the Excel Application for 2 seconds - Application.Wait Now() + #12:00:01 AM# - - - With WrdApp.Selection - .PasteExcelTable LinkedToExcel:=True, WordFormatting:=True, RTF:=True - End With - - Set WrdTbl = WrdDoc.Tables(WrdDoc.Tables.Count) - WrdTbl.AllowAutoFit = True - WrdTbl.AutoFitBehavior (wdAutoFitWindow) - WrdTbl.Spacing = 19 - WrdTbl.Shading.BackgroundPatternColorIndex = wdBlue - - - 'Create a new page - WrdApp.ActiveDocument.Sections.Add - - 'Go to the newly created page - WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToNext - - 'Clear my clipboard - Application.CutCopyMode = False - - Next - - WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToFirst - -End Sub +Option Explicit + +Sub CopyTableToWord_Single() + + 'Declare Word Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + Dim WrdTbl As Word.Table + + 'Declare Excel Variables + Dim ExcLisObj As ListObject + + 'Create a new instance of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new document in my application + Set WrdDoc = WrdApp.Documents.Add + + 'Define ListObject + Set ExcLisObj = ActiveSheet.ListObjects(1) + + 'Create a reference to the range I want to Copy. + ExcLisObj.Range.Copy + + 'Pause the Excel Application for 2 seconds + Application.Wait Now() + #12:00:01 AM# + + + With WrdApp.Selection + .PasteExcelTable LinkedToExcel:=True, WordFormatting:=True, RTF:=True + End With + + Set WrdTbl = WrdDoc.Tables(WrdDoc.Tables.Count) + WrdTbl.AllowAutoFit = True + WrdTbl.AutoFitBehavior (wdAutoFitWindow) + WrdTbl.Spacing = 19 + WrdTbl.Shading.BackgroundPatternColorIndex = wdBlue + + + 'Create a new page + WrdApp.ActiveDocument.Sections.Add + + 'Go to the newly created page + WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToNext + + 'Clear my clipboard + Application.CutCopyMode = False + + + WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToFirst + +End Sub + +Sub CopyTableToWord_Multi() + + 'Declare Word Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + Dim WrdTbl As Word.Table + + 'Declare Excel Variables + Dim ExcLisObj As ListObject + + 'Create a new instance of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new document in my application + Set WrdDoc = WrdApp.Documents.Add + + 'Loop through each element in the range array + For Each ExcLisObj In ActiveSheet.ListObjects + + 'Create a reference to the range I want to Copy. + ExcLisObj.Range.Copy + + 'Pause the Excel Application for 2 seconds + Application.Wait Now() + #12:00:01 AM# + + + With WrdApp.Selection + .PasteExcelTable LinkedToExcel:=True, WordFormatting:=True, RTF:=True + End With + + Set WrdTbl = WrdDoc.Tables(WrdDoc.Tables.Count) + WrdTbl.AllowAutoFit = True + WrdTbl.AutoFitBehavior (wdAutoFitWindow) + WrdTbl.Spacing = 19 + WrdTbl.Shading.BackgroundPatternColorIndex = wdBlue + + + 'Create a new page + WrdApp.ActiveDocument.Sections.Add + + 'Go to the newly created page + WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToNext + + 'Clear my clipboard + Application.CutCopyMode = False + + Next + + WrdApp.Selection.GoTo What:=wdGoToPage, which:=wdGoToFirst + +End Sub diff --git a/vba/word-vba/Align Shapes In Word.bas b/vba/vba-word/Word - Align Shapes.bas similarity index 96% rename from vba/word-vba/Align Shapes In Word.bas rename to vba/vba-word/Word - Align Shapes.bas index 90041aa..125d98d 100644 --- a/vba/word-vba/Align Shapes In Word.bas +++ b/vba/vba-word/Word - Align Shapes.bas @@ -1,119 +1,119 @@ -Attribute VB_Name = "Practice" -Sub ExportingToWord_MultiplePages() - - 'Declare Word Variables - Dim WrdApp As Word.Application - Dim WrdDoc As Word.Document - Dim WrdRng As Word.Range - Dim WrdShp As Word.InlineShape - - 'Declare Excel Variables - Dim ChrtObj As ChartObject - - 'Create a new instance of Word - Set WrdApp = New Word.Application - WrdApp.Visible = True - WrdApp.Activate - - 'Create a new word document - Set WrdDoc = WrdApp.Documents.Open("C:\Users\Alex\Desktop\MyWordDoc.docx") - - 'Loop through the charts on the active sheet - Set ChrtObj = ActiveSheet.ChartObjects(1) - - 'Copy the chart - ChrtObj.Chart.ChartArea.Copy - - 'PASTE TO A BOOKMARK - Set WrdRng = WrdDoc.Bookmarks("MyChartPosition").Range - - Application.Wait Now() + #12:00:03 AM# - - With WrdRng - .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine - End With - - Set WrdShp = WrdDoc.InlineShapes(1) - - With WrdShp - .Height = WrdApp.InchesToPoints(1.5) - .Width = WrdApp.InchesToPoints(2.5) - End With - - 'PASTE TO A PARAGRAPH - Set WrdRng = WrdDoc.Paragraphs(4).Range - WrdRng.Collapse Direction:=wdCollapseStart - - With WrdRng - .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine - .ParagraphFormat.SpaceAfter = 40 - .ParagraphFormat.SpaceBefore = 40 - End With - - Set WrdShp = WrdDoc.InlineShapes(2) - - With WrdShp - .Height = WrdApp.InchesToPoints(1.5) - .Width = WrdApp.InchesToPoints(2.5) - End With - - 'PASTE TO SECOND PAGE IN THE SECOND PARAGRAPH - Set WrdRng = WrdDoc.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=2) - Set WrdRng = WrdRng.Next(Unit:=wdParagraph) - WrdRng.Collapse Direction:=wdCollapseStart - - With WrdRng - .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine - End With - - Set WrdShp = WrdDoc.InlineShapes(3) - - With WrdShp - .Height = WrdApp.InchesToPoints(1.5) - .Width = WrdApp.InchesToPoints(2.5) - .Range.ParagraphFormat.Alignment = wdAlignParagraphRight - End With - - 'PASTE TO SECTION - Set WrdRng = WrdDoc.Sections(2).Range.Paragraphs(2).Range - WrdRng.Collapse Direction:=wdCollapseStart - - With WrdRng - .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine - End With - - 'PASTE INSIDE WORDS - Set WrdRng = WrdDoc.Paragraphs(1).Range.Words(10) - WrdRng.Collapse Direction:=wdCollapseStart - - With WrdRng - .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine - End With - - Set WrdShp = WrdDoc.InlineShapes(1) - - With WrdShp - .Height = WrdApp.InchesToPoints(1.5) - .Width = WrdApp.InchesToPoints(2.5) - End With - - - - 'Clear the Clipboard - Application.CutCopyMode = False - - Set WrdRng = Nothing - -End Sub - - - -' Set WrdShp = WrdDoc.InlineShapes(WrdDoc.InlineShapes.Count) -' -' WrdShp.Select -' -' With WrdApp.Selection.ShapeRange -' .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage -' .RelativeVerticalPosition = wdRelativeHorizontalPositionMargin -' End With - +Attribute VB_Name = "Practice" +Sub ExportingToWord_MultiplePages() + + 'Declare Word Variables + Dim WrdApp As Word.Application + Dim WrdDoc As Word.Document + Dim WrdRng As Word.Range + Dim WrdShp As Word.InlineShape + + 'Declare Excel Variables + Dim ChrtObj As ChartObject + + 'Create a new instance of Word + Set WrdApp = New Word.Application + WrdApp.Visible = True + WrdApp.Activate + + 'Create a new word document + Set WrdDoc = WrdApp.Documents.Open("C:\Users\Alex\Desktop\MyWordDoc.docx") + + 'Loop through the charts on the active sheet + Set ChrtObj = ActiveSheet.ChartObjects(1) + + 'Copy the chart + ChrtObj.Chart.ChartArea.Copy + + 'PASTE TO A BOOKMARK + Set WrdRng = WrdDoc.Bookmarks("MyChartPosition").Range + + Application.Wait Now() + #12:00:03 AM# + + With WrdRng + .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine + End With + + Set WrdShp = WrdDoc.InlineShapes(1) + + With WrdShp + .Height = WrdApp.InchesToPoints(1.5) + .Width = WrdApp.InchesToPoints(2.5) + End With + + 'PASTE TO A PARAGRAPH + Set WrdRng = WrdDoc.Paragraphs(4).Range + WrdRng.Collapse Direction:=wdCollapseStart + + With WrdRng + .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine + .ParagraphFormat.SpaceAfter = 40 + .ParagraphFormat.SpaceBefore = 40 + End With + + Set WrdShp = WrdDoc.InlineShapes(2) + + With WrdShp + .Height = WrdApp.InchesToPoints(1.5) + .Width = WrdApp.InchesToPoints(2.5) + End With + + 'PASTE TO SECOND PAGE IN THE SECOND PARAGRAPH + Set WrdRng = WrdDoc.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=2) + Set WrdRng = WrdRng.Next(Unit:=wdParagraph) + WrdRng.Collapse Direction:=wdCollapseStart + + With WrdRng + .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine + End With + + Set WrdShp = WrdDoc.InlineShapes(3) + + With WrdShp + .Height = WrdApp.InchesToPoints(1.5) + .Width = WrdApp.InchesToPoints(2.5) + .Range.ParagraphFormat.Alignment = wdAlignParagraphRight + End With + + 'PASTE TO SECTION + Set WrdRng = WrdDoc.Sections(2).Range.Paragraphs(2).Range + WrdRng.Collapse Direction:=wdCollapseStart + + With WrdRng + .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine + End With + + 'PASTE INSIDE WORDS + Set WrdRng = WrdDoc.Paragraphs(1).Range.Words(10) + WrdRng.Collapse Direction:=wdCollapseStart + + With WrdRng + .PasteSpecial DataType:=wdPasteMetafilePicture, Placement:=wdInLine + End With + + Set WrdShp = WrdDoc.InlineShapes(1) + + With WrdShp + .Height = WrdApp.InchesToPoints(1.5) + .Width = WrdApp.InchesToPoints(2.5) + End With + + + + 'Clear the Clipboard + Application.CutCopyMode = False + + Set WrdRng = Nothing + +End Sub + + + +' Set WrdShp = WrdDoc.InlineShapes(WrdDoc.InlineShapes.Count) +' +' WrdShp.Select +' +' With WrdApp.Selection.ShapeRange +' .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage +' .RelativeVerticalPosition = wdRelativeHorizontalPositionMargin +' End With + diff --git a/vba/word-vba/Working With Building Blocks.bas b/vba/vba-word/Word - Building Blocks Object.bas similarity index 100% rename from vba/word-vba/Working With Building Blocks.bas rename to vba/vba-word/Word - Building Blocks Object.bas diff --git a/vba/word-vba/Working With Documents.bas b/vba/vba-word/Word - Document Object.bas similarity index 100% rename from vba/word-vba/Working With Documents.bas rename to vba/vba-word/Word - Document Object.bas diff --git a/vba/word-vba/Working With the Find Object.bas b/vba/vba-word/Word - Find Object.bas similarity index 100% rename from vba/word-vba/Working With the Find Object.bas rename to vba/vba-word/Word - Find Object.bas diff --git a/vba/word-vba/Headers & Footers.bas b/vba/vba-word/Word - Headers & Footers - Object.bas similarity index 100% rename from vba/word-vba/Headers & Footers.bas rename to vba/vba-word/Word - Headers & Footers - Object.bas diff --git a/vba/word-vba/Loop Through Words.bas b/vba/vba-word/Word - Navigate Words.bas similarity index 100% rename from vba/word-vba/Loop Through Words.bas rename to vba/vba-word/Word - Navigate Words.bas diff --git a/vba/word-vba/Working With Paragraphs.bas b/vba/vba-word/Word - Paragraph Object.bas similarity index 100% rename from vba/word-vba/Working With Paragraphs.bas rename to vba/vba-word/Word - Paragraph Object.bas diff --git a/vba/word-vba/Count Lines In Doc.bas b/vba/vba-word/Word - Statistics.bas similarity index 100% rename from vba/word-vba/Count Lines In Doc.bas rename to vba/vba-word/Word - Statistics.bas diff --git a/vba/word-vba/Working With Templates.bas b/vba/vba-word/Word - Template Object.bas similarity index 100% rename from vba/word-vba/Working With Templates.bas rename to vba/vba-word/Word - Template Object.bas