Logicwurks Home Page

Links To Excel Code Examples

Tracing VBA Statements
Range/Wkb/Wks Variables
Add Grand Totals Using Ranges
Using Range Offset Property
Using Range Find Method
ConvertCellAddressToRange
Set Conditional Formatting
Union Of Ranges
Parse Range Strings
Delete Duplicate Rows
Delete Rows And Columns
Worksheet Variables
TypeName And TypeOf
Loop Through Worksheets
Loop Through Open Workbooks
Form Button Magic
Command Button Magic
Add Worksheets Dynamically
ImportExternalWorksheets
Find Last Row Or Column
Copy And Paste Special
Copy To Specific Cell Types
Range Copy With Filter
ExcelFileOpenSaveClose
ExcelFileOpenSaveCSV
Open An Excel File
Open An Excel File w/Params
Open An Excel File On Web
Save A Workbook
Save A Workbook Using mso
Clone A Workbook
Test If WEB URL Exists
Parse Using Split Command
Using Classes in Excel
TypeStatementStructures
Color Management
Convert Cell Color To RGB
Sort Methods 2003 - 2010
Sort Alpha/Numeric In ASCII
Search Using Match Function
Search Using Vlookup Function
Search Using Xlookup Function
Using Find Instead of Vlookup
Remove String Non-Printables
Auto_Open And Auto_Close
Initialize Form At Open
Edit Numerics In UserForm
Load Combo And List Boxes
Floating Sheet Combo Boxes
Advanced User Form Coding
Excel Events
Worksheet Change Events
Binary Search Of Array
Typecast Constants
Excel Error Handling
Handling Optional Parameters
Data Validation Drop Downs
Insert Data Validation Sub
Read A Text File w/Handle
Write A Text File w/Handle
Read a Binary File w/Handle
Update a Binary File w/Handle
Binary File Copy and Update
Read A Text Fiile w/Script
Text File Processing Examples
Test For Exists Or Open
Splash Screen
Dynamically Load Formulas
PaymentStreamsByDate
Date Examples
Date Find Same Days
Convert Month To Number
Initialize Arrays
Load Arrays Using Evaluate
ChartsAndGraphsVBA
Redim An Array
Reassign Button Action
Timer Functions
Legacy Calendar Control
Excel 2010 Date Picker
Date Picker Alternative
Generate Multiple Worksheets
Read Access Data Into Excel
Send Outlook Email w/Attach
Copy AutoFilters To Sheets
Export A Text File
Get Windows User Name
VBA Format Statement
Manipulate Files via VBA
Dynamically Load Images
Loop Through Worksheet Objects
Loop Through Form Objects
Loop Through Files with DIR
Active-X Checkboxes
Add Forms Checkboxes Dynam
Paste Pictures Into Excel
Copy Pictures Sheet To Sheet
Copy Pictures Sheet To Sheet
Create Forms Buttons With VBA
Extract Filename From Path
Convert R1C1 Format to A1
Special Cells Property
Insert Cell Comments

Links To Access Code Examples

DAO Versus ADODB
SearchVBACodeStrings
Interface Excel With Access
Create Form Manually
Create Recordset With AddNew
Multi-Select List Boxes
Update Field(s) In A Recordset
Update Excel Pivot From Access
Import A Tab Delimited File
Export Excel FileDialog
Create Excel Within Access
Open Excel Within Access
Open Excel OBJ From Access
Format Excel From Access
Control Excel via Access VBA
On Error Best Practices
Import Tab Delim w/WinAPI
Initialize Global Variables
Using TempVars For Globals
Access Error Handling
Loop Through Form Controls
Insert A Calendar Control
Create A Filtered Recordset
Populate Combo Boxes
Bookmarks And Forms
Combo Box Multiple Sources
Passing Form Objects
Create VBA SQL Statements
Create Dynamic Queries
Display File Images On A Form
Manipulate Files via VBA
Manipulate Files via Scripting
Number Subform Records
Reference Subform Objects
Parse Delimited Fields
Parameterized Queries (VBA)
Manipulating QueryDefs In VBA
FindFirst On Combined Keys
Dlookup Command
Dlookup In Form Datasheet
Execute SQL Delete Records
Commit Form To Table
Report With No Data
Reference Form Objects
DSNLess Connections To MySQL
Print Active Form Record
Count Records in Linked Tables
Delete Empty Tables
Open Linked SQL Tables

 

This demonstrates linking to Excel from Access And Updating a Pivot Table

Syntax Examples

Option Compare Database
Option Explicit
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Dim strDirectoryLevel1 As String
Dim strDirectoryLevel2 As String
Dim strCurrentDir As String
Dim strUserName As String

Private Sub cmdCreateReport_Click()
' **************************************************************
' Establish Database Query Connection
' **************************************************************
Dim db As DAO.Database
Dim recIn As DAO.Recordset

' **************************************************************
' Establish Excel Communications from Access
' **************************************************************
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlSelectedMovementData As Excel.Worksheet
Dim xlPivotTableWorksheet As Excel.Worksheet
Dim xlPivotTable As PivotTable
Dim xlPivotCache As PivotCache

Dim rngDataRange          As Range
Dim strPivotName          As String
Dim strNewRange           As String
Dim rngStartPoint         As Range
Dim rngNewRange           As Range
Dim strNewRangeString     As String
Dim lngLastRow            As Long
Dim lngLastColumn         As Long
Dim rngLastCell           As Range


' **************************************************************
' Other Variables
' **************************************************************
Dim lngRowCount As Long
Dim strSavedFileName As String

' **************************************************************
' Validate Date Input
' **************************************************************
If Me.txtFromDate = "" Or IsNull(Me.txtFromDate) Then
    MsgBox ("A From date is required")
    Exit Sub
End If

If Year(Me.txtFromDate) < 2017 Then
    MsgBox ("From Date Year Must Be 2017 or Greater")
    Exit Sub
End If

If Me.txtToDate = "" Or IsNull(Me.txtToDate) Then
    MsgBox ("A To date is required")
    Exit Sub
End If

If Year(Me.txtToDate) < 2017 Then
    MsgBox ("To Date Year Must Be 2017 or Greater")
    Exit Sub
End If

If Me.txtFromDate >= Me.txtToDate Then
    MsgBox ("From Date Must Be Less Than To Date")
    Exit Sub
End If

If Me.frmReportSelection <> 1 Then
    MsgBox ("This reports is waiting to be devloped")
    Exit Sub
End If

' **************************************************************
' Save selected from and to dates to the global area
' **************************************************************
gblDateFrom = Me.txtFromDate
gblDateTo = Me.txtToDate

' **************************************************************
' Set up error handling
' **************************************************************
On Error GoTo Error_Handler:

' **************************************************************
' Verify That The Movement Template Exists
' **************************************************************
If Not FileExists("C:\BeerMovementTemplate\BeerMovementsReportTemplateV1.xlsx") Then
    MsgBox ("Template C:\BeerMovementTemplate\BeerMovementsReportTemplateV1.xlsx Does Not Exist")
    Exit Sub
End If

DoCmd.Hourglass True

' **************************************************************
' Open the Excel Beer Movement Ticket Template
' **************************************************************
Set xlApp = New Excel.Application
Set xlWB = xlApp.Workbooks.Open("C:\BeerMovementTemplate\BeerMovementsReportTemplateV1.xlsx")
Set xlSelectedMovementData = xlWB.Sheets("BeerMovementData")
Set xlPivotTableWorksheet = xlWB.Sheets("Data Pivot")
Set xlPivotTable = xlPivotTableWorksheet.PivotTables("MovementsPivot")
Set xlPivotCache = xlPivotTable.PivotCache

' **************************************************************
' Populate the Template With Beer Movement Data
' **************************************************************
' ***********************************************************************
' Open the Movement Query
' ***********************************************************************
Set db = CurrentDb()
Set recIn = db.OpenRecordset("qryForDateRangeBeerMovementPivot")

' ***********************************************************************
' Clear Existing Data in Template
' ***********************************************************************
xlSelectedMovementData.Rows("2:100").EntireRow.Delete
lngRowCount = 1

xlPivotTableWorksheet.Range("C1").Value = gblDateFrom & " Thru " & gblDateTo

' ***********************************************************************
' Loop Through Each Record And Populate The Excel Form
' ***********************************************************************
Do
' ***************************************************************
' Insert the beer movements into the BeerMovementsData worksheet
' ***************************************************************
    lngRowCount = lngRowCount + 1
    
    xlSelectedMovementData.Cells(lngRowCount, "A") = recIn!OakshireSerialNumber
    xlSelectedMovementData.Cells(lngRowCount, "B") = recIn!MovementDate
    xlSelectedMovementData.Cells(lngRowCount, "C") = recIn!ItemID
    xlSelectedMovementData.Cells(lngRowCount, "D") = recIn!ItemDescription
    xlSelectedMovementData.Cells(lngRowCount, "E") = recIn!SalesQty
    xlSelectedMovementData.Cells(lngRowCount, "F") = recIn!PackageDescription
    xlSelectedMovementData.Cells(lngRowCount, "G") = recIn!PackageType
    xlSelectedMovementData.Cells(lngRowCount, "H") = recIn!TotalBBLS
    xlSelectedMovementData.Cells(lngRowCount, "I") = recIn!Keg_Case
    xlSelectedMovementData.Cells(lngRowCount, "J") = recIn!BBLSInKegs
    xlSelectedMovementData.Cells(lngRowCount, "K") = recIn!BBLSInCases
    xlSelectedMovementData.Cells(lngRowCount, "L") = recIn!SiteFrom
    xlSelectedMovementData.Cells(lngRowCount, "M") = recIn!SiteTo
    xlSelectedMovementData.Cells(lngRowCount, "N") = recIn!Carrier
    xlSelectedMovementData.Cells(lngRowCount, "O") = recIn!Brand
    recIn.MoveNext
    Loop Until recIn.EOF

recIn.Close
Set recIn = Nothing
Set db = Nothing

' xlApp.Visible = True (Keep it invisible)
' ********************************************************
' Look up the updated last row and column after
' Access updated the data. Convert To a Range
' ********************************************************
lngLastRow = xlSelectedMovementData.Cells(xlSelectedMovementData.Rows.Count, "A").End(xlUp).Row
lngLastColumn = xlSelectedMovementData.Cells(1, xlSelectedMovementData.Columns.Count).End(xlToLeft).Column
Set rngLastCell = xlSelectedMovementData.Cells(lngLastRow, lngLastColumn)

Set rngStartPoint = xlSelectedMovementData.Range("A1")
Set rngNewRange = xlSelectedMovementData.Range(rngStartPoint, rngLastCell)

' ********************************************************
' Set up the new range string used by ChangePivotCache
' ********************************************************
strNewRangeString = xlWB.Path & "\" & "[" & xlWB.Name & "]" & "BeerMovementData!" & rngNewRange.Address(ReferenceStyle:=xlR1C1)

' ********************************************************
' Ask Excel to change the pivot table's data source
' ********************************************************
xlPivotTableWorksheet.PivotTables("MovementsPivot").ChangePivotCache xlWB. _
    PivotCaches.Create(SourceType:=xlDatabase, SourceData:=(strNewRangeString), Version:=xlPivotTableVersion15)

' ********************************************************
' Tidy up with refreshes of the pivot table
' ********************************************************
  xlPivotTableWorksheet.PivotTables("MovementsPivot").RefreshTable
  xlPivotTableWorksheet.PivotTables("MovementsPivot").PivotCache.Refresh
  xlPivotTableWorksheet.PivotTables("MovementsPivot").Update

' ***********************************************************************
' Print The Worksheet PO
' ***********************************************************************
xlPivotTableWorksheet.PrintOut

' **************************************************************
' Set Up Save Directory To Save The File
' This will only create a directory if one doesn't exist
' **************************************************************
Call CreateRegulatoryReportsDirectories

strSavedFileName = strDirectoryLevel2 & "Movement Summary" & "-" & Year(Me.txtFromDate) & "-" & Format(Month(Me.txtFromDate), "00") & "-" & Format(Day(Me.txtFromDate), "00") _
   & " Thru " & Year(Me.txtToDate) & "-" & Format(Month(Me.txtToDate), "00") & "-" & Format(Day(Me.txtToDate), "00")

' **************************************************************
' Save it to the network drive
' **************************************************************
xlPivotTableWorksheet.PivotTables("MovementsPivot").SaveData = True
xlWB.SaveAs FileName:=strSavedFileName, FileFormat:=xlOpenXMLWorkbook

' **************************************************************
' If User Decides to also save a PDF, put code here
' **************************************************************

' **************************************************************
' Close the file
' **************************************************************
xlApp.DisplayAlerts = False
xlWB.Close SaveChanges:=False
xlApp.DisplayAlerts = True
'xlApp.Quit
'Set xlApp = Nothing

' **************************************************************
' Close the remaining objects
' **************************************************************
Error_Handler_Exit:
On Error Resume Next
If Not xlWB Is Nothing Then
    xlApp.DisplayAlerts = False
    xlWB.Close SaveChanges:=False
    xlApp.DisplayAlerts = True
    Set xlWB = Nothing
End If

If Not xlApp Is Nothing Then
    xlApp.Quit
    Set xlApp = Nothing
End If
If Not recIn Is Nothing Then
    recIn.Close
    Set recIn = Nothing
End If
If Not db Is Nothing Then Set db = Nothing
DoCmd.Hourglass False
Exit Sub

Error_Handler:
MsgBox "An Error Occurred In This Application" & vbCrLf & _
   "Please Contact The Developer" & vbCrLf & vbCrLf & _
   "Error Number = " & Err.Number & "  Error Description = " & _
    Err.Description, vbCritical

Resume Error_Handler_Exit

End Sub

Public Function CreateRegulatoryReportsDirectories()

strDirectoryLevel1 = "O:\Regulatory Reports " & Year(gblDateFrom)
strDirectoryLevel2 = strDirectoryLevel1 & "\" & Format(Month(gblDateFrom), "00") & " - " & MonthName(Month(gblDateFrom)) & "\"

strUserName = UserNameWindows()

If Not FolderExists(strDirectoryLevel1) Then
    MkDir (strDirectoryLevel1)
End If

If Not FolderExists(strDirectoryLevel2) Then
    MkDir (strDirectoryLevel2)
End If

End Function

Public Function FolderExists(FolderPath As String) As Boolean
' *******************************************************************************************
' * THIS FUNCTION WILL TEST IF A FOLDER EXISTS                                              *
' *******************************************************************************************
On Error GoTo err_In_Locate

' ***********************************************************
' * See If A Folder Exists                                  *
' ***********************************************************
  FolderExists = (Len(Dir(FolderPath, vbDirectory)) > 0)
    
mod_ExitFunction:
  Exit Function
  
' ***************************************************
' * Error Correction Routines                       *
' ***************************************************
err_In_Locate:
  FolderExists = False
  Resume mod_ExitFunction
  
End Function

Public Function FileExists(FilePath As String) As Boolean
' *******************************************************************************************
' * THIS FUNCTION WILL TEST IF A FILE EXISTS - Doesn't Work on a networked Drive            *
' *******************************************************************************************
On Error GoTo err_In_Locate
  
' ***********************************************************
' * See If A File Exists - Provide The Full Path to the File
' ***********************************************************
FileExists = (Len(Dir(FilePath)) > 0)
  
mod_ExitFunction:
  Exit Function
  
' ***************************************************
' * Error Correction Routines                       *
' ***************************************************
err_In_Locate:
  FileExists = False
  Resume mod_ExitFunction
  
End Function

Public Function DeleteFile(SourceFile As String) As Boolean
' *******************************************************************************************
' * DELETE A FILE                                                                           *
' *******************************************************************************************

' *******************************************************************
' * (1) This function will delete a file                            *
' * (2) A full path to the file being deleted is recommended        *
' * (3) If you omit the path, Access looks in the CurDir for the    *
' *     file to be deleted                                          *
' *******************************************************************
  
On Error GoTo err_In_Delete
  
  Kill SourceFile
  DeleteFile = True
  
mod_ExitFunction:
  Exit Function
  
' ***************************************************
' * File To Be Deleted Does Not Exist               *
' ***************************************************
err_In_Delete:
  DeleteFile = False
  Resume mod_ExitFunction
    
End Function

Function UserNameWindows() As String
    
    Dim lngLen As Long
    Dim strBuffer As String
    
    Const dhcMaxUserName = 255
    
    strBuffer = Space(dhcMaxUserName)
    lngLen = dhcMaxUserName
    If CBool(GetUserName(strBuffer, lngLen)) Then
        UserNameWindows = Left$(strBuffer, lngLen - 1)
    Else
        UserNameWindows = ""
    End If
End Function