On this blog I add random but select VBA functions, subprocedures and subroutines that I'd consider similar or comparable to the ones that I used over time to resolve various automation issues in Excel and Access via VBA based macros to handle challenging tasks that I had to grapple with at work. I gather these code snippets from around multiple sources and display them here as kind of a collection of code library to provide a showcase of how I utilized VBA in real life and also as a reference source.
'Place the code below into the standard module Sub ArrayTest() Dim arrValue(1 To 100, 1 To 2) As Integer Dim varTest As Variant Dim intCounter As Integer, intTest As Integer intTest = CInt(InputBox("Controldigit enter:", , 5)) For intCounter = 1 To 100 arrValue(intCounter, 1) = intCounter arrValue(intCounter, 2) = intCounter * 10 Next intCounter varTest = Application.VLookup(intTest, arrValue, 2, 0) If IsError(varTest) Then Beep MsgBox "Value Not Found!" Else MsgBox "Value: " & varTest End If End Sub
'Place the following user defined function in a standard VBA module Function SplitHype(rng As Range, iInfo As Integer) Select Case iInfo Case 0: SplitHype = rng.Value Case 1: SplitHype = rng.Hyperlinks(1).Address Case 2: SplitHype = rng.Hyperlinks(1).SubAddress End Select End Function
'Place the below UDF(user defined function)in a standard VBA module. Function CountColor(rng As Range, iColor As Integer) Dim rngAct As Range Dim iCount As Integer For Each rngAct In rng.Cells If rngAct.Interior.ColorIndex = iColor And _ Not IsEmpty(rngAct) Then iCount = iCount + 1 End If Next rngAct CountColor = iCount End Function Formula is =countcolor(A1:C6,6)
'Place the code below into the standard module Sub File_exists() Dim dName$ dName = "c:exceltest.xls" If Dir(dName) <> "" Then MsgBox dName & " exists!" Else MsgBox dName & " does not exist!" End If End Sub
'Place the code below into the standard module Sub Reference() Range("A2").Formula = _ "=VLOOKUP(A1,'c:excel[test1.xls]Sheet1'!A1:B4,2,0)" End Sub
'Place the code below into the standard module Sub BuildSum() Dim z%, i% Cells(20, 8).Select z = ActiveCell.Row For i = 1 To 7 Cells(z - 1 + i, 6).FormulaArray = _ "=SUM((r2c1:r23c2=1)*(r2c3:r23c3=" & i & ")*(r2c[-2]:r23c[-2]))" Next i End Sub
Private Sub Worksheet_Change(ByVal Target As Range)If Not Intersect(Target, Range("A1:A5")) Is Nothing Then Range("A1:A5").Sort Range("A1"), xlAscending, Header:=xlYesEnd IfEnd Sub
Microsoft added this long anticipated function to Excel early part of the 2020. XLOOKUP replaces the old VLOOKUP and offers a whole lot more power and flexibility. I added to Sample Excel Macros section a file to illustrate various different ways of utilizing this valuable function.
On my Projects > Sample Excel Files section I added a file RangeComparison1.xlsx. If curious you may want to open this file and check it for yourself. Change a cell value anywhere in either of the ranges on Sheet1 or Sheet2 then click on the button located on Sheet1. If there is a change i.e. ranges are not identical then VBA will generate another Excel file indicating where the difference is and will highlight in red color, if data is exactly the same then VBA will tell you that as well. There were times that I had to deal with comparing two data sets and tried to use many convoluted and cumbersome formula based methods after I got sick and tired of that process and I have started using this method where applicable.
Put the below code in a standard module then assign it to a button. Sub Link2Value() Dim rng As Range For Each rng In ActiveSheet.UsedRange.Cells If rng.HasFormula Then If InStr(rng.Formula, "[") Then rng.Value = rng.Value End If End If Next rngEnd Sub
Extracting a year from text is possible using string functions if the location of the year is fixed in the text within each cell. But in a free form sentence where the year is used anywhere according to the context there is no way of knowing where in the cell the year is located. In this case UDF (user defined function) created in VBA solves the issue and it is stored like another Excel built-in function so typing the name of this function is sufficient in the fomula line. Refer to the file on macro samples for this example called ExtractYerFromText.xls. Below is the code used to create the said UDF.Function GetYear(txt As String) As Integer Dim intCounter As Integer txt = txt & " " For intCounter = 1 To Len(txt) - 4 If Mid(txt, intCounter, 5) Like "*#### *" Then GetYear = Mid(txt, intCounter, 4) Exit Function End If Next intCounterEnd Function Note - - UDF as entered would be =GetYear(A2) Assigned to a forms button: Sub YearCaller() Dim x As Integer x = GetYear(Range("A2").Value) MsgBox xEnd Sub
Use this code block in the standard module to print the range without blank rows in it. Sub PrintRows() Dim TB As Worksheet Dim i%, lRow% Application.ScreenUpdating = False Set TB = Worksheets("Sheet1") lRow = TB.[a16384].End(xlUp).Row For i = 1 To lRow If IsEmpty(TB.Cells(i, 1)) Then TB.Rows(i).EntireRow.Hidden = True Next i TB.PrintPreview TB.Range(TB.Cells(1, 1), TB.Cells(lRow, 1)).EntireRow.Hidden = FalseApplication.ScreenUpdating = TrueEnd Sub
Problem:I have two Excel files like File A and File B, I need to create a batch process to run on my desktop where File A is linked to Access database and File B contains the updated records to be copied into File A so once File A gets updated Access table which is linked to it will be updated as well.
Option Explicit Dim xlApp, xlFileA, xlFileB Dim wsA, wsB Dim lastRowA, lastRowB Dim fileAPath, fileBPath ' Define the file paths fileAPath = "C:\path\to\FileA.xlsx" ' Update with the correct path to File A fileBPath = "C:\path\to\FileB.xlsx" ' Update with the correct path to File B ' Create Excel application object Set xlApp = CreateObject("Excel.Application") xlApp.Visible = False xlApp.DisplayAlerts = False ' Open both Excel files Set xlFileA = xlApp.Workbooks.Open(fileAPath) Set xlFileB = xlApp.Workbooks.Open(fileBPath) ' Set worksheet references Set wsA = xlFileA.Sheets(1) ' Adjust sheet number if necessary Set wsB = xlFileB.Sheets(1) ' Adjust sheet number if necessary ' Get last row in both worksheets lastRowA = wsA.Cells(wsA.Rows.Count, 1).End(-4162).Row ' -4162 is equivalent to xlUp in VBA lastRowB = wsB.Cells(wsB.Rows.Count, 1).End(-4162).Row ' Copy data from File B (Source) to File A (Destination) wsB.Range("A1:Z" & lastRowB).Copy wsA.Cells(lastRowA + 1, 1) ' Adjust the range accordingly ' Save and close the workbooks xlFileA.Save xlFileA.Close xlFileB.Close ' Quit Excel xlApp.Quit ' Release objects Set wsA = Nothing Set wsB = Nothing Set xlFileA = Nothing Set xlFileB = Nothing Set xlApp = Nothing
Sub RunQueriesWithResponse() DoCmd.SetWarnings False DoCmd.OpenQuery "YourQuery1" DoCmd.OpenQuery "YourQuery2" DoCmd.SetWarnings True ' Variable to capture the user's response Dim response As Integer response = MsgBox("Do you want to continue?", vbQuestion + vbYesNo, "Continue?") ' Check the response If response = vbYes Then MsgBox "User chose to continue!", vbInformation Else MsgBox "User chose to stop.", vbCritical End If End Sub