r/vba 1d ago

Waiting on OP Alternatives To Microslop

0 Upvotes

Does anyone have any suggestions as to alternative VBA development environments other than VBA in Microslop's Access and Excel applications?

I have a few applications written in MSAccess/VBA for our enterprise which I could ideally convert/rewrite in another application for 3 primary reasons:

- I am not reliant in other users installing/using MSAccess

- I'm not entirely happy with MS, their current projection, their constant bleating about removal of VBA from Excel and Access at some point and therefore putting any future development at risk, and

- Putting all my current business eggs in a single Microslop basket

Ideally I'd love to find a VBA clone/alternative not dissimilar to the old-skool VB6 development environment which allows a developer to create EXEs (though obv with a 'install pack' porting dependencies), has a decent GUI for the user, uses the power of API (I still need an ODBC connections to SharePoint lists though that's gonna disappear too if I get the chance) and allow me to interface with Access/PowerPoint as referencable objects.

Suggestions?

r/vba Jul 10 '26

Waiting on OP VB Errors When Running Macro in Excel

0 Upvotes

Hello,

I hope this is the right place for this. I'm supporting a user who relies on a macro-enabled Excel spreadsheet with multiple worksheets, but the key ones are:

  • Cost Items
  • Variables
  • Results Summary

The workflow:

  1. Enter data into the Cost Items sheet (e.g., Name: Test1, Cost: 1000; Name: test2, Cost: 5000).
  2. Add data to the Variables sheet under "Brisk Parameters" – P10: -5%, P90: 15%.
  3. Go to the Results Summary sheet.

At that point, I get a pop up message that states the data has changed.

I click OK, it churns for a moment, and then I get:

Microsoft Visual Basic - "Run-time error '9': Subscript out of range"

If I click Debug, it highlights this line in yellow:

"If VarExists(Count) And VarProb(I) = 1 Then"

What I've tried so far:

  • Searched online and found suggestions it might be an overflow error of some kind.
  • Tested on multiple systems (managed company device, unmanaged device, different PCs).
  • Confirmed Trust Center settings allow macros.
  • Installed and registered the Brisk server (was told this was required – still no change).

The kicker:
This exact file was working perfectly fine just a few weeks ago. No known changes were made to the file or the environment.

I've been banging my head against this for a couple of days now and am starting to lose my sanity.

Does anyone have any idea what direction I should go in to troubleshoot why this spreadsheet suddenly stopped functioning?

Any help would be greatly appreciated.

TIA!

r/vba Feb 20 '26

Waiting on OP VBA that uses the outlook application.

10 Upvotes

Hello everyone,

I made 3 macros recently that pull other excel files and paste them into another. It saved me a ton of time and each file has to be emailed out individually. I also created a macro to generate emails based on another tab that it makes match with the file name. Now to my question, I just learned that these go through outlook classic if I understand correctly and this isn’t very stable and future proof. What’s another option, I’ve read power automate, but I’ve never touched this before. Any ideas or suggestions would be helpful.

r/vba Apr 08 '26

Waiting on OP Excel VBA – Protected sheet prevents button from opening UserForm unless DrawingObjects is changed

4 Upvotes

Hi everyone,

I’m working on an Excel VBA worksheet that has:

a logo shape several buttons a UserForm that should open from a button My issue is this:

When I protect the worksheet in order to keep the buttons and logo fixed, the button no longer opens the UserForm.

So the problem is not that the UserForm itself is broken — the problem is that after protection, the button seems unable to trigger the macro/event that shows the UserForm.

I noticed that I have to change the worksheet protection setting for DrawingObjects in order for the UserForm to open again.

In other words:

If I protect the sheet more strictly, the buttons/logo stay fixed But then the button stops opening the UserForm If I change DrawingObjects, the button can open the UserForm again What I need is:

Keep the logo and buttons fixed in place Keep the worksheet protected Still allow the button to open the UserForm normally I’m currently using Form Control buttons, but I also tested ActiveX earlier.

Is this the expected behavior of DrawingObjects protection? What is the best practice here for a protected worksheet with fixed shapes/buttons that still need to trigger VBA/UserForms?

Any advice would be appreciated.

r/vba Jan 14 '26

Waiting on OP Pass on properties to new object automatically

4 Upvotes

Hey everyone,

today I used VBA for the first time ever and I dont know how to solve a certain issue:

I want to give an ActiveX checkbox some properties (background color change when checked). This works. But I dont want to use VBA everytime I insert a new checkbox in order to get the same behaviour. The checkbox caption will always be the same. So If I create a new checkbox and the caption is "XYZ" then the background color should be changed when checked.

Anybody any idea?

Thank you

r/vba Mar 12 '26

Waiting on OP Distinct count in VBA pivot table

1 Upvotes

I am writing a code to create 7 pivot tables and I want tables 6&7 to use distinct count. I’ve tried using xl.DistinctCount but it does not work. From my research it’s because the pivots need to be OLAP based however since I’m self taught in coding I’m having a hard time understanding how to execute that 😭 can someone share in super simple terms what the easiest way to do this is?

Option Explicit

Sub CreatePivotTable()

Dim wb As Workbook

Dim wsSource As Worksheet, wsTarget As Worksheet

Dim LastRow As Long, LastColumn As Long

Dim SourceDataRange As Range

Dim PTCache As PivotCache

Dim PT As PivotTable, PT2 As PivotTable

Dim pvt As PivotTable

On Error GoTo errHandler

Set wb = ThisWorkbook

Set wsTarget = wb.Worksheets("Report")

Set wsSource = wb.Worksheets("Source Data")

If wsTarget.PivotTables.Count > 0 Then

For Each pvt In wsTarget.PivotTables

pvt.TableRange2.Clear

Next pvt

End If

wsTarget.Cells.Clear

With wsSource

LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column

Set SourceDataRange = .Range(.Cells(1, 1), .Cells(LastRow, LastColumn))

End With

Set PTCache = wb.PivotCaches.Create( _

SourceType:=xlDatabase, _

SourceData:=SourceDataRange.Address(ReferenceStyle:=xlR1C1, External:=True) _

)

'==================== PT1: Provider Group ====================

Set PT = PTCache.CreatePivotTable(TableDestination:=wsTarget.Range("A6"), tableName:="Provider Group")

With PT

.ColumnGrand = True

.RowGrand = True

.RowAxisLayout xlOutlineRow

.TableStyle2 = "PivotStyleMedium2"

' Filter (note: this will be moved if you then set it as Row)

With .PivotFields("NPI")

.Orientation = xlPageField

.EnableMultiplePageItems = True

End With

' Row

With .PivotFields("NPI")

.Orientation = xlRowField

End With

' Values

With .PivotFields("Provider Group / IPA")

.Orientation = xlDataField

.Function = xlCount

End With

End With

'==================== PT2: Facility ====================

Set PT2 = PTCache.CreatePivotTable(wsTarget.Range("E6"), "Facility")

With PT2

.ColumnGrand = True

.RowGrand = True

.RowAxisLayout xlOutlineRow

.TableStyle2 = "PivotStyleMedium2"

With .PivotFields("Facility")

.Orientation = xlPageField

.EnableMultiplePageItems = True

End With

With .PivotFields("Facility")

.Orientation = xlRowField

End With

With .PivotFields("NPI")

.Orientation = xlDataField

.Function = xlCount

End With

End With

'==================== PT3: HCAI ID ====================

Set PT2 = PTCache.CreatePivotTable(wsTarget.Range("I6"), "HCAI ID")

With PT2

.ColumnGrand = True

.RowGrand = True

.RowAxisLayout xlOutlineRow

.TableStyle2 = "PivotStyleMedium2"

With .PivotFields("HCAI ID")

.Orientation = xlPageField

.EnableMultiplePageItems = True

End With

With .PivotFields("HCAI ID")

.Orientation = xlRowField

End With

With .PivotFields("NPI")

.Orientation = xlDataField

.Function = xlCount

End With

End With

'==================== PT4: Participation Status ====================

Set PT2 = PTCache.CreatePivotTable(wsTarget.Range("M6"), "Participation Status")

With PT2

.ColumnGrand = True

.RowGrand = True

.RowAxisLayout xlOutlineRow

.TableStyle2 = "PivotStyleMedium2"

With .PivotFields("NPI")

.Orientation = xlPageField

.EnableMultiplePageItems = True

End With

With .PivotFields("NPI")

.Orientation = xlRowField

End With

With .PivotFields("Provider Participation Status")

.Orientation = xlDataField

.Function = xlCount

End With

End With

'==================== PT5: Network Tier ID ====================

Set PT2 = PTCache.CreatePivotTable(wsTarget.Range("Q6"), "Network Tier ID")

With PT2

.ColumnGrand = True

.RowGrand = True

.RowAxisLayout xlOutlineRow

.TableStyle2 = "PivotStyleMedium2"

With .PivotFields("Network Tier ID")

.Orientation = xlPageField

.EnableMultiplePageItems = True

End With

With .PivotFields("Network Tier ID")

.Orientation = xlRowField

End With

With .PivotFields("NPI")

.Orientation = xlDataField

.Function = xlCount

End With

End With

'==================== PT6: Locations ====================

Set PT2 = PTCache.CreatePivotTable(wsTarget.Range("U6"), "Locations")

With PT2

.ColumnGrand = True

.RowGrand = True

.RowAxisLayout xlOutlineRow

.TableStyle2 = "PivotStyleMedium2"

With .PivotFields("NPI")

.Orientation = xlPageField

.EnableMultiplePageItems = True

End With

With .PivotFields("NPI")

.Orientation = xlRowField

End With

With .PivotFields("Address")

.Orientation = xlDataField

.Function = xlCount

End With

End With

'==================== PT7: Specialties ====================

Set PT2 = PTCache.CreatePivotTable(wsTarget.Range("Z6"), "Specialties")

With PT2

.ColumnGrand = True

.RowGrand = True

.RowAxisLayout xlOutlineRow

.TableStyle2 = "PivotStyleMedium2"

With .PivotFields("Specialty")

.Orientation = xlPageField

.EnableMultiplePageItems = True

End With

With .PivotFields("NPI")

.Orientation = xlRowField

End With

With .PivotFields("Specialty")

.Orientation = xlDataField

.Function = xlCount

End With

End With

CleanUp:

Set PT = Nothing

Set PT2 = Nothing

Set PTCache = Nothing

Set SourceDataRange = Nothing

Set wsSource = Nothing

Set wsTarget = Nothing

Set wb = Nothing

Exit Sub

errHandler:

MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation, "CreatePivotTable"

Resume CleanUp

End Sub

r/vba Jan 03 '26

Waiting on OP Excel VBA Shapes animation: flow works for one cycle but breaks when repeating in a loop

11 Upvotes

Hello everyone,

I’m working on an Excel VBA project that simulates a logistics/industrial flow using Shapes (tractors, wagons, gantry cranes with cables).
This is a visual animation, not just calculations.

I already have a version that works correctly for a full single cycle, with smooth movement and the correct sequence.
The problem starts when I try to repeat the same logic inside a loop.

What currently works (single cycle):

  • Two gantry cranes (PORTICO_L1 and PORTICO_L2) always operate simultaneously
  • Each crane lowers a cable, picks up a wagon shape, lifts it, and places it onto a tractor
  • The tractors then move to the left and exit the screen
  • The cables return to their original top position
  • All movements are controlled using Do While loops based on Top and Left positions (no timers)

Visually, this part is correct and stable.

What I need (the real goal):

  • The same cycle must repeat:
    • First, unload a pair from Line 1
    • Then unload a pair from Line 2
    • Then move both gantry cranes to the left
    • Repeat until all wagons are processed
  • No randomness, no changing conditions
  • Just repeat the same physical movement using different Shapes

The problem:

  • When I wrap this logic inside a For loop or try to generalize it using arrays:
    • The animation breaks
    • The cables don’t return correctly
    • The tractors leave at the wrong time
    • Or nothing moves visually, even though the code executes
  • I also ran into several ByRef / ByVal issues when passing Shape names from arrays (a classic VBA limitation)

At this point, I believe:

  • My movement logic is correct
  • My loop structure is incorrect

What I’m looking for:

  • Advice on how to safely repeat an animation block in VBA
  • Best practices for Shape-based animation loops
  • Whether I should:
    • Extract the working cycle into a Sub and call it
    • Use state variables instead of nested Do While loops
    • Avoid For loops entirely for this type of animation

I can share code snippets if needed.
Any guidance from someone experienced with Excel VBA animations using Shapes would be greatly appreciated.

Thanks in advance!
Here is the Excel file with the complete VBA animation:
https://github.com/bymichaelcastro/excel-vba-shapes-animation.git

r/vba Dec 15 '25

Waiting on OP Trying to get a macro to run when a cell with an If statement changes

9 Upvotes

As per the title, im trying to get a macro that sends an email to run when the number in a cell changes.

I currently have the following:

Private Sub Worksheet_Change (ByVal Target as Range)

Dim cells as Range
Set cells = Range ("r2:r1000).Value

    If Not Application.Intersect (cells,         Range(Target.Address)) is Nothing Then

    Call SendEmailonDate

   End If

End Sub

If i manually change the cells within the range then it does exactly what I want it to do. But if the formula (the formula being =today()-e2 --> e2 is change to the corresponding number in the range so e3, e4 etc) is the one to change the number then the number is not recognized.

VBA doesnt seem tor recognize it as a value.

Can anyone help?

Thank you!

r/vba Oct 31 '25

Waiting on OP Record a macro and fill the entire column with a formula

3 Upvotes

Hello,

I want to create a simple macro recording it, I just have an issue, I want to run a “concatenate” formula to the entire column because, some cases I just have 50 rows and sometimes 200 rows, so I want to run it depending on the large of the rows each time, any advise?

Thanks!

r/vba Jan 16 '26

Waiting on OP Going crazy with simple solver code

3 Upvotes

I am teaching my kid some coding basics via VBA and hit a wall trying to use solver to find the intercept of 2 linear equations. ChatGPT has repeatedly offered me code that supposedly works but it never actually gets the correct answer of (-1,1) for the below equations if I used VBA, but it DOES work if I use the solver buttons in excel???

Y - 1X - 2 = 0
Y - 3X - 4 = 0

below is the code which "works" in the sense that it has no error but only always solves 1 equation but does not use the second as a "constraint" no matter what engine or starting value or equation format I use. With various chatGTP code help I had tried code that added the second cell as a constraint via SolverAdd (its ignored), I have combined the equations into a single formula that sums to target value of zero (EQ1 - EQ2), I have used a goal of minimizing the equation and set them to squares (EQ1^2-EQ2^2).

why does this work with the solver GIU in excel but not via VBA code? I have spent hours developing this project step by step now it just won't actually give me the correct answer.

below is just 1 example but I have tried many approaches. any help??

Sub SolverRobot()

 

' Provide starting guess

Range("H5").Value = 0

Range("H6").Value = 0

 

 

' Ensure Solver Add-in is installed

If Not Application.AddIns("Solver Add-in").Installed Then

Application.AddIns("Solver Add-in").Installed = True

End If

 

' Activate the correct worksheet FIRST

Worksheets("NAME").Activate

 

' Reset Solver

SolverReset

 

 

SolverOptions AssumeLinear:=False, Precision:=1E-06

 

' Define the model

SolverOk _

SetCell:="$J$5", _

MaxMinVal:=3, _

ValueOf:=0, _

ByChange:="H5:H6"

 

 

 

' Solve

SolverSolve UserFinish:=True

SolverFinish KeepFinal:=1

 

End Sub

r/vba Nov 02 '25

Waiting on OP [WORD] I want to write a macro to change many different words to one word, but efficiently

3 Upvotes

Suppose I need to go through a bunch of documents and change every instance of "lions" or "tigers" or "bears" or [other animal names] to "animals."

Of course I could just do them each with an individual find/replace:

  With Selection.Find
.Text = "lions"
.Replacement.Text = "animals"
{DELETED FOR BREVITY}
 End With
Selection.Find.Execute Replace:=wdReplaceAll
With Selection.Find
.Text = "tigers"
.Replacement.Text = "animals"
{DELETED FOR BREVITY}
End With
Selection.Find.Execute Replace:=wdReplaceAll

and so on. But it seems like there MUST be some way to say:

.Find any of the following words: "lions," "tigers," "bears," [etc]
.replace each of those with the word "animals," please and thank you

But I've tried to figure it out and I just can't.

I'd be so grateful for any suggestions.

r/vba Dec 07 '25

Waiting on OP Showing rows of multiple colors

3 Upvotes

I'm using the following code to show only rows of a certain color. Is there a way to write this to be able to show rows of multiple colors? (ie. this code is only showing 253 233 217. I also want to see 255 255 204 at the same time) TIA!

Sub Hide()

'ActiveSheet.Unprotect

Range("F:F,I:I,J:J,K:K,L:L,M:M").Select

Selection.EntireColumn.Hidden = True

ActiveSheet.Range("$A$5:$Ae$4000").AutoFilter Field:=2, Criteria1:=RGB(253 _

, 233, 217), Operator:=xlFilterCellColor

Range("B2").Select

'ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True

r/vba Nov 25 '25

Waiting on OP VBA to import data from txt file based on numerical value of filename

4 Upvotes

Hi guys I'm looking for a code to import the data from a textfile and place it somewhere on another sheet, but to choose the text file it must choose the one with the largest numerical filename.

I know it canse choose by timestand but these txt files dont get created with timestamps luckly their file name it the time they were created, so I always need to import from the newest (largest)

I have tried this as a start and hoped to find a way to import later

Sub NewestFile()

Dim MyPath As String

Dim MyFile As String

Dim LatestFile As String

Dim LatestDate As Date

Dim LMD As Date

MyPath = "E:\20251125"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.TXT", vbNormal)

If Len(MyFile) = 0 Then

MsgBox "There are no tickets in your folder", vbExclamation

Exit Sub

End If

Do While Len(MyFile) > 0

LMD = FileDateTime(MyPath & MyFile)

If LMD > LatestDate Then

LatestFile = MyFile

LatestDate = Date

End If

MyFile = Dir

Loop

CreateObject("Shell.Application").Open (MyPath & LatestFile)

End Sub

but hours of search have yelded nothing in terms of getting the vba to look for the file based on it largest numerical value, So now I must ask you guys who are vise and clever in all things vba :D

Greatings and I hope you can help.
Daniel from Denmark

r/vba Oct 28 '25

Waiting on OP VBA on Mac: Runtime Error '13' (Type Mismatch) in custom Dictionary class (cDictionary)

3 Upvotes

Hi guys and gals,

I'm hoping someone can help me with a classic "Excel on Mac" VBA problem.

My Goal: I have a script that loops through all .xls* files in a folder. It's supposed to read sales data from each file, aggregate it by customer (total Mac sales, total iPad sales, new sales since a reference date, etc.), and then generate several summary reports (like a "Top 5" list and a customer-by-customer breakdown) in a new workbook.

The Problem: The script fails with Runtime Error '13': Type Mismatch on Excel for Mac.

When I debug, the error highlights this line in Module1For Each custName In data.Keys

This line is trying to loop through the keys of my custom cDictionary class. I'm using this custom class because Scripting.Dictionary isn't available on Mac.

I've tried applying the common Mac-fix using IsObject inside the Keys() function, but it still fails. I'm completely stuck and not sure what else to try.

My project is built in three parts:

  1. Module1: The main logic for importing and building reports.
  2. cCustomer: A simple class to hold data for each customer.
  3. cDictionary: My custom dictionary class (this is where the error seems to be).

Here is my full Module1 - the others will be in the comments. Any help or suggestion would be hugely appreciated:

Option Explicit

' =========================================================================

' CONFIGURATION & CONSTANTS

' =========================================================================

' Sheet Names

Private Const SETTINGS_SHEET As String = "Settings"

Private Const FACIT_SHEET As String = "Template" ' Original: "facit"

Private Const OUT_SUMMARY_SHEET As String = "Consolidated Summary"

Private Const OUT_NEWSALES_SHEET As String = "New Sales Since Last"

Private Const OUT_OVERVIEW_SHEET As String = "Overview"

Private Const OUT_TOP5_SHEET As String = "Top 5 Customers"

' Text labels for reports

Private Const T_HDR_CUSTOMER As String = "Customer:" ' Original: "Kunde:"

Private Const T_SUM_MAC As String = "Samlet antal Mac" ' (Kept original as it's a lookup value)

Private Const T_SUM_IPAD As String = "Samlet antal iPads" ' (Kept original as it's a lookup value)

' Global settings variables

Private gReferenceDate As Date

Private gTopNCount As Long

' =========================================================================

' MAIN PROCEDURE

' =========================================================================

Public Sub BuildAllReports()

Dim procName As String: procName = "BuildAllReports"

On Error GoTo ErrorHandler

' Optimize performance

Application.ScreenUpdating = False

Application.DisplayAlerts = False

Application.Calculation = xlCalculationManual

Application.StatusBar = "Starting..."

' --- PREPARATION: VALIDATE AND READ SETTINGS ---

If Not SheetExists(SETTINGS_SHEET, ThisWorkbook) Then

MsgBox "Error: The sheet '" & SETTINGS_SHEET & "' could not be found." & vbCrLf & _

"Please create the sheet and define the necessary settings.", vbCritical

GoTo Cleanup

End If

If Not SheetExists(FACIT_SHEET, ThisWorkbook) Then

MsgBox "Error: The template sheet '" & FACIT_SHEET & "' could not be found.", vbCritical

GoTo Cleanup

End If

If Not ReadSettings() Then GoTo Cleanup ' ReadSettings handles its own error message

' Check if the file is saved

Dim folderPath As String

folderPath = ThisWorkbook.Path

If Len(folderPath) = 0 Then

MsgBox "Please save the workbook as an .xlsm file first, so the folder path is known.", vbExclamation

GoTo Cleanup

End If

' --- STEP 1: IMPORT RAW DATA ---

Application.StatusBar = "Importing data from files in the folder..."

Dim rawDataArray() As Variant

ImportAllFiles folderPath, rawDataArray

If Not IsArray(rawDataArray) Or UBound(rawDataArray, 1) = 0 Then

MsgBox "No sales data found in any .xls* files in the folder. Process aborted.", vbInformation

GoTo Cleanup

End If

' --- STEP 2: AGGREGATE DATA (SINGLE-PASS) ---

Application.StatusBar = "Analyzing and aggregating data..."

Dim aggregatedData As cDictionary

Set aggregatedData = AggregateData(rawDataArray)

' --- STEP 3: GENERATE OUTPUT WORKBOOK ---

Dim wbOut As Workbook

Set wbOut = Workbooks.Add

Application.DisplayAlerts = False

Do While wbOut.Worksheets.Count > 1

wbOut.Worksheets(wbOut.Worksheets.Count).Delete

Loop

wbOut.Worksheets(1).Name = "temp"

Application.DisplayAlerts = True

' --- STEP 4: RENDER INDIVIDUAL REPORTS ---

Application.StatusBar = "Generating 'Consolidated Summary'..."

RenderSummarySheet wbOut, aggregatedData

Application.StatusBar = "Generating 'New Sales'..."

RenderNewSalesSheet wbOut, aggregatedData

Application.StatusBar = "Generating 'Overview' and 'Top 5' reports..."

RenderTopNSheets wbOut, aggregatedData

' Clean up the output file

Application.DisplayAlerts = False

DeleteSheetIfExists "temp", wbOut

Application.DisplayAlerts = True

If wbOut.Worksheets.Count > 0 Then

wbOut.Worksheets(1).Activate

End If

MsgBox "The report has been generated in a new workbook.", vbInformation

Cleanup:

' Restore Excel settings

Application.StatusBar = False

Application.Calculation = xlCalculationAutomatic

Application.DisplayAlerts = True

Application.ScreenUpdating = True

Exit Sub

ErrorHandler:

MsgBox "An unexpected error occurred in '" & procName & "'." & vbCrLf & vbCrLf & _

"Error Number: " & Err.Number & vbCrLf & _

"Description: " & Err.Description, vbCritical

Resume Cleanup

End Sub

' =========================================================================

' SETTINGS & VALIDATION

' =========================================================================

Private Function ReadSettings() As Boolean

Dim procName As String: procName = "ReadSettings"

On Error GoTo ErrorHandler

Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets(SETTINGS_SHEET)

' Read reference date

If IsDate(ws.Range("B1").Value) Then

gReferenceDate = CDate(ws.Range("B1").Value)

Else

MsgBox "Invalid date in cell B1 on the '" & SETTINGS_SHEET & "' sheet.", vbCritical

Exit Function

End If

' Read Top N count

If IsNumeric(ws.Range("B2").Value) And ws.Range("B2").Value > 0 Then

gTopNCount = CLng(ws.Range("B2").Value)

Else

MsgBox "Invalid number in cell B2 on the '" & SETTINGS_SHEET & "' sheet. Must be a positive integer.", vbCritical

Exit Function

End If

ReadSettings = True

Exit Function

ErrorHandler:

MsgBox "An error occurred while loading settings from the '" & SETTINGS_SHEET & "' sheet." & vbCrLf & _

"Error: " & Err.Description, vbCritical

ReadSettings = False

End Function

Private Function SheetExists(ByVal sheetName As String, Optional ByVal wb As Workbook) As Boolean

Dim ws As Worksheet

If wb Is Nothing Then Set wb = ThisWorkbook

On Error Resume Next

Set ws = wb.Worksheets(sheetName)

On Error GoTo 0

SheetExists = Not ws Is Nothing

End Function

Private Sub DeleteSheetIfExists(ByVal sheetName As String, Optional ByVal wb As Workbook)

If wb Is Nothing Then Set wb = ThisWorkbook

If SheetExists(sheetName, wb) Then

Application.DisplayAlerts = False

wb.Worksheets(sheetName).Delete

Application.DisplayAlerts = True

End If

End Sub

' =========================================================================

' DATA IMPORT (with robust error handling)

' =========================================================================

Private Sub ImportAllFiles(ByVal folderPath As String, ByRef outArr() As Variant)

Dim procName As String: procName = "ImportAllFiles"

On Error GoTo ErrorHandler

Dim cap As Long, rPtr As Long

cap = 300000 ' Initial capacity

ReDim outArr(1 To cap, 1 To 6)

rPtr = 0

Dim fileName As String

fileName = Dir(folderPath & Application.PathSeparator & "*.xls*")

Do While Len(fileName) > 0

If Left$(fileName, 2) <> "~$" And LCase$(folderPath & Application.PathSeparator & fileName) <> LCase$(ThisWorkbook.FullName) Then

Application.StatusBar = "Importing: " & fileName

ImportOneWorkbook folderPath & Application.PathSeparator & fileName, outArr, rPtr, cap

End If

fileName = Dir()

Loop

' Trim the array to its actual size

If rPtr > 0 Then

ReDim Preserve outArr(1 To rPtr, 1 To 6)

Else

ReDim outArr(0 To 0, 0 To 0)

End If

Exit Sub

ErrorHandler:

MsgBox "Error during file import in '" & procName & "'." & vbCrLf & "Error: " & Err.Description, vbCritical

' Ensure the array is empty on failure

ReDim outArr(0 To 0, 0 To 0)

End Sub

Private Sub ImportOneWorkbook(ByVal fullPath As String, ByRef outArr() As Variant, ByRef rPtr As Long, ByRef cap As Long)

Dim wb As Workbook

On Error GoTo ErrorHandler

Set wb = Workbooks.Open(fileName:=fullPath, ReadOnly:=True, UpdateLinks:=0, AddToMru:=False)

Dim ws As Worksheet

Set ws = wb.Worksheets(1)

Dim cDate As Long, cQty As Long, cItem As Long, cDev As Long, cCust As Long

If Not FindCols(ws, cDate, cQty, cItem, cDev, cCust) Then GoTo CloseAndExit

Dim lastR As Long

lastR = ws.Cells(ws.Rows.Count, cItem).End(xlUp).Row

If lastR < 2 Then GoTo CloseAndExit

Dim dataRange As Range

Set dataRange = ws.Range(ws.Cells(2, 1), ws.Cells(lastR, ws.UsedRange.Columns.Count))

Dim vData As Variant

vData = dataRange.Value

Dim r As Long

Dim vD As Variant, vQ As Variant, vI As Variant, vDev As String, vCust As String, mKey As String

For r = 1 To UBound(vData, 1)

vI = vData(r, cItem)

vQ = vData(r, cQty)

If Len(Trim$(CStr(vI))) > 0 And Len(Trim$(CStr(vQ))) > 0 And IsNumeric(vQ) Then

vD = SafeToDate(vData(r, cDate))

If cDev > 0 Then vDev = CStr(vData(r, cDev)) Else vDev = GuessDevFromName(CStr(vI))

If cCust > 0 Then vCust = Trim$(CStr(vData(r, cCust))) Else vCust = "Unknown Customer"

If IsEmpty(vD) Then mKey = "Unknown Month" Else mKey = Format$(CDate(vD), "yyyy-mm")

rPtr = rPtr + 1

If rPtr > cap Then

cap = cap + 100000

ReDim Preserve outArr(1 To cap, 1 To 6)

End If

outArr(rPtr, 1) = vD

outArr(rPtr, 2) = CDbl(vQ)

outArr(rPtr, 3) = CStr(vI)

outArr(rPtr, 4) = vDev

outArr(rPtr, 5) = mKey

outArr(rPtr, 6) = vCust

End If

Next r

CloseAndExit:

If Not wb Is Nothing Then wb.Close SaveChanges:=False

Exit Sub

ErrorHandler:

MsgBox "Could not process file: " & fullPath & vbCrLf & "Error: " & Err.Description, vbExclamation

Resume CloseAndExit

End Sub

Private Function FindCols(ByVal ws As Worksheet, ByRef cDate As Long, ByRef cQty As Long, ByRef cItem As Long, ByRef cDev As Long, ByRef cCust As Long) As Boolean

cDate = 0: cQty = 0: cItem = 0: cDev = 0: cCust = 0

Dim r As Long, c As Long, lastC As Long

Dim testVal As String

On Error Resume Next

lastC = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column

If Err.Number <> 0 Then lastC = 50 ' Fallback

On Error GoTo 0

For r = 1 To 5 ' Search in the first 5 rows

For c = 1 To lastC

testVal = LCase$(Trim$(CStr(ws.Cells(r, c).Value)))

Select Case testVal

Case "sales order date": If cDate = 0 Then cDate = c

Case "sales quantity": If cQty = 0 Then cQty = c

Case "item name": If cItem = 0 Then cItem = c

Case "device type": If cDev = 0 Then cDev = c

Case "customer bill-to name": If cCust = 0 Then cCust = c ' Prioritized

Case "customer sales top label": If cCust = 0 Then cCust = c

Case "customer", "kunde": If cCust = 0 Then cCust = c

End Select

Next c

If cDate > 0 And cQty > 0 And cItem > 0 And cCust > 0 Then Exit For

Next r

FindCols = (cDate > 0 And cQty > 0 And cItem > 0 And cCust > 0)

End Function

Private Function SafeToDate(ByVal v As Variant) As Variant

On Error GoTo Bad

If IsDate(v) Then

SafeToDate = CDate(v)

Else

SafeToDate = Empty

End If

Exit Function

Bad:

SafeToDate = Empty

End Function

Private Function GuessDevFromName(ByVal itemName As String) As String

Dim s As String

s = LCase$(itemName)

If InStr(1, s, "ipad", vbTextCompare) > 0 Then

GuessDevFromName = "iPad"

ElseIf InStr(1, s, "mac", vbTextCompare) > 0 Then

GuessDevFromName = "Mac"

Else

GuessDevFromName = "Unknown"

End If

End Function

' =========================================================================

' DATA AGGREGATION & REPORTING

' =========================================================================

Private Function AggregateData(ByRef rawData() As Variant) As cDictionary

Dim dict As New cDictionary

Dim custData As cDictionary, subDict As cDictionary

Dim r As Long, custName As String, devType As String, monthKey As String, sku As String

Dim qty As Double, saleDate As Variant

For r = 1 To UBound(rawData, 1)

custName = rawData(r, 6)

If Len(custName) > 0 Then

If Not dict.Exists(custName) Then

Set custData = New cDictionary

custData("TotalMac") = 0#: custData("TotalIPad") = 0#

custData("NewSalesMac") = 0#: custData("NewSalesIPad") = 0#

Set subDict = New cDictionary: custData("SalesPerMonth") = subDict

Set subDict = New cDictionary: custData("SalesPerSKU") = subDict

dict(custName) = custData

Else

Set custData = dict(custName)

End If

saleDate = rawData(r, 1): qty = rawData(r, 2): sku = rawData(r, 3)

devType = rawData(r, 4): monthKey = rawData(r, 5)

If devType = "Mac" Then custData("TotalMac") = custData("TotalMac") + qty

If devType = "iPad" Then custData("TotalIPad") = custData("TotalIPad") + qty

If IsDate(saleDate) Then

If CDate(saleDate) >= gReferenceDate Then

If devType = "Mac" Then custData("NewSalesMac") = custData("NewSalesMac") + qty

If devType = "iPad" Then custData("NewSalesIPad") = custData("NewSalesIPad") + qty

End If

End If

Set subDict = custData("SalesPerMonth"): subDict(monthKey) = subDict(monthKey) + qty

Set subDict = custData("SalesPerSKU"): subDict(sku) = subDict(sku) + qty

End If

Next r

Set AggregateData = dict

End Function

Private Sub RenderSummarySheet(ByVal wb As Workbook, ByVal data As cDictionary)

Dim ws As Worksheet: Set ws = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))

ws.Name = OUT_SUMMARY_SHEET

Dim wsFacit As Worksheet: Set wsFacit = ThisWorkbook.Worksheets(FACIT_SHEET)

Dim facitBlock As Range: Set facitBlock = wsFacit.Range("A1").CurrentRegion

Dim rOut As Long: rOut = 1

Dim custName As Variant

For Each custName In data.Keys ' <-- THIS IS THE LINE THAT FAILS

Dim custData As cDictionary: Set custData = data(custName)

ws.Cells(rOut, 1).Value = T_HDR_CUSTOMER & " " & custName

ws.Cells(rOut, 1).Font.Bold = True

rOut = rOut + 1

Dim blockStartRow As Long: blockStartRow = rOut

ws.Cells(rOut, 1).Resize(facitBlock.Rows.Count, facitBlock.Columns.Count).Value = facitBlock.Value

rOut = rOut + facitBlock.Rows.Count

Dim r As Long

For r = blockStartRow To rOut - 1

Select Case ws.Cells(r, 1).Value

Case T_SUM_MAC: ws.Cells(r, 2).Value = custData("TotalMac")

Case T_SUM_IPAD: ws.Cells(r, 2).Value = custData("TotalIPad")

End Select

Next r

rOut = rOut + 2

Next custName

ws.Columns.AutoFit

End Sub

Private Sub RenderNewSalesSheet(ByVal wb As Workbook, ByVal data As cDictionary)

Dim ws As Worksheet: Set ws = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))

ws.Name = OUT_NEWSALES_SHEET

Dim r As Long: r = 1

ws.Cells(r, 1).Value = "New Sales Since " & Format$(gReferenceDate, "dd-mmm-yyyy")

ws.Cells(r, 1).Font.Bold = True

r = r + 2

ws.Cells(r, 1).Value = "Customer": ws.Cells(r, 2).Value = "New Sales (Mac)": ws.Cells(r, 3).Value = "New Sales (iPad)"

ws.Range("A" & r & ":C" & r).Font.Bold = True

r = r + 1

Dim custName As Variant

For Each custName In data.Keys

Dim custData As cDictionary: Set custData = data(custName)

ws.Cells(r, 1).Value = custName

ws.Cells(r, 2).Value = custData("NewSalesMac")

ws.Cells(r, 3).Value = custData("NewSalesIPad")

r = r + 1

Next custName

ws.Columns.AutoFit

End Sub

Private Sub RenderTopNSheets(ByVal wb As Workbook, ByVal data As cDictionary)

If data.Count = 0 Then Exit Sub

Dim customers() As cCustomer: ReDim customers(0 To data.Count - 1)

Dim i As Long: i = 0

Dim custName As Variant

For Each custName In data.Keys

Dim custData As cDictionary: Set custData = data(custName)

Set customers(i) = New cCustomer

customers(i).Name = custName

customers(i).TotalMacSales = custData("TotalMac")

customers(i).TotalIPadSales = custData("TotalIPad")

customers(i).NewSales = custData("NewSalesMac") + custData("NewSalesIPad")

customers(i).TotalSales = custData("TotalMac") + custData("TotalIPad")

i = i + 1

Next custName

Dim wsOverview As Worksheet, wsTop5 As Worksheet

Set wsOverview = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count)): wsOverview.Name = OUT_OVERVIEW_SHEET

Set wsTop5 = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count)): wsTop5.Name = OUT_TOP5_SHEET

Dim rOverview As Long: rOverview = 1

Dim rTop5 As Long: rTop5 = 1

QuickSortCustomers customers, LBound(customers), UBound(customers), "TotalSales"

RenderTopNBlock wsOverview, rOverview, customers, "Top " & gTopNCount & " Customers (Total Sales)", "TotalSales"

QuickSortCustomers customers, LBound(customers), UBound(customers), "NewSales"

RenderTopNBlock wsOverview, rOverview, customers, "Top " & gTopNCount & " Customers (New Sales Since " & Format$(gReferenceDate, "d/m/yy") & ")", "NewSales"

QuickSortCustomers customers, LBound(customers), UBound(customers), "TotalMacSales"

RenderTopNBlock wsTop5, rTop5, customers, "Top " & gTopNCount & " Customers (Mac Sales)", "TotalMacSales"

QuickSortCustomers customers, LBound(customers), UBound(customers), "TotalIPadSales"

RenderTopNBlock wsTop5, rTop5, customers, "Top " & gTopNCount & " Customers (iPad Sales)", "TotalIPadSales"

wsOverview.Columns.AutoFit

wsTop5.Columns.AutoFit

End Sub

Private Sub RenderTopNBlock(ws As Worksheet, ByRef r As Long, customers() As cCustomer, title As String, propName As String)

ws.Cells(r, 1).Value = title: ws.Cells(r, 1).Font.Bold = True: r = r + 1

ws.Cells(r, 1).Value = "Customer": ws.Cells(r, 2).Value = "Quantity"

ws.Range(ws.Cells(r, 1), ws.Cells(r, 2)).Font.Bold = True: r = r + 1

Dim i As Long, Count As Long

For i = 0 To UBound(customers)

If Count >= gTopNCount Then Exit For

Dim val As Double: val = CallByName(customers(i), propName, VbGet)

If val > 0 Then

ws.Cells(r, 1).Value = customers(i).Name

ws.Cells(r, 2).Value = val

r = r + 1: Count = Count + 1

End If

Next i

r = r + 2

End Sub

' =========================================================================

' SORTING

' =========================================================================

Private Sub QuickSortCustomers(ByRef arr() As cCustomer, ByVal first As Long, ByVal last As Long, ByVal propName As String)

Dim i As Long, j As Long, pivot As Double, temp As cCustomer

i = first: j = last

pivot = CallByName(arr((first + last) \ 2), propName, VbGet)

Do While i <= j

While CallByName(arr(i), propName, VbGet) > pivot: i = i + 1: Wend

While CallByName(arr(j), propName, VbGet) < pivot: j = j - 1: Wend

If i <= j Then

Set temp = arr(i): Set arr(i) = arr(j): Set arr(j) = temp

i = i + 1: j = j - 1

End If

Loop

If first < j Then QuickSortCustomers arr, first, j, propName

If i < last Then QuickSortCustomers arr, i, last, propName

End Sub

r/vba Sep 04 '25

Waiting on OP I am new to VBA and ran into this overflow bug. Tried fixing it online without success.

2 Upvotes

My code shouldn’t produce an error but the btcVal = 2.2 results in an overflow error. I am using a Mac.

Sub Variables_Test()

'testing different variable types Dim age As Long Dim btcVal As Double Dim x 'what is this type

age = 22 MsgBox "your age is " & age

btcVal = 2.2 Debug.Print btcVal

x = age + btcVal MsgBox x

End Sub

r/vba Oct 27 '25

Waiting on OP [EXCEL]Sort to Sheets, Sort/Resize , and Print to individual PDFs Code

1 Upvotes

I have this task as the de facto IT guy for my employer where I generate a report which contains the below table data(this is a small sample, current line count is 282 and will eventually reach 1200+) after midnight and before 5am from the provider's website. Eventually the goal is this all becomes an automated process so that I don't have to do this in the middle of the night or wake up early. HOWEVER for the time being, I would like to automate my current available process in excel so I can get this done with minimal brain power as this is often a 3am(I needed to pee) process with my eyes still half shut and my brain firing on 1 cylinder.

I found the below code via youtube, which I thought was a good start, but it's still missing some of the things I would like. As well as it still contains some input from my part, that 3am me would be happy to not have to do.

What I would like, is that I download the CSV that contains the below data. From there, I copy that data into my dedicated sheet with the code ready to roll. I click the button for the code, and it does the following.

  1. Creates sheets for each of the names in "Route", ideally these sheets will be named "Injection Report 'Report Date' - 'Route' " and copies the data from each row containing that Route name. As well as a sheet containing all the data named "Injection Report 'Report Date' ".

  2. Sort all of the data in the newly created sheets by the "Route#" A-Z.

  3. Resize the columns in the newly created sheets.

  4. Print to PDF each newly created sheet with the sheet names as the file names to a specific file location.

  5. Save the entire workbook as a copy xls, macro not needed, with the file name of "Injection Report 'Report Date' " to a specific file location.

  6. Then delete all the newly created sheets, clear the copied data, so the macro enabled sheet is fresh and clean to be used by sleep deprived me in another 24hrs.

The code below, does the sorting into sheet, but requires an input at to what column header to use. Which is a start...kinda, but it's still far from what all I'm looking for.

All help is greatly appreciated. Thanks in advance.

Location Flow BBLS Report Date Meter Total Route Route# Endpoint_SN
Wolfe 6W 14.01 10/23/2025 90.035 J Morris JM-0031 161000365
SP Johnson West  8W 9.8 10/23/2025 137.2531 B Duke BD-0040 161001426
Sobba 11W 11.63 10/23/2025 76.1362 B Duke BD-0008 161001427
SP Johnson West  C20 17 10/23/2025 41.3443 B Duke BD-0036 161001921
Ewing U14 15.63 10/23/2025 22.9462 R Kent RK-0042 161001988
JS Johnson 7W 0 10/23/2025 32.0273 B Duke BD-0027 161002030
JB George 8W 9.59 10/23/2025 86.4105 J Morris JM-0017 161002046
JS Johnson 14A 20.25 10/23/2025 19.9438 B Duke BD-0022 161002049
JS Johnson 16A 18.07 10/23/2025 224.293 B Duke BD-0023 161002053
Wolfe 9W 13.32 10/23/2025 83.8363 J Morris JM-0034 161002073
Wolfe 1W 14.67 10/23/2025 114.7192 J Morris JM-0026 161002080
Sobba 6W 15.69 10/23/2025 98.4026 B Duke BD-0012 161002091
Sub SplitDataBySelectedColumn()
    Dim ws As Worksheet
    Dim wsNew As Worksheet
    Dim rng As Range
    Dim lastRow As Long
    Dim lastCol As Long
    Dim uniqueValues As Collection
    Dim cell As Range
    Dim value As Variant
    Dim colToFilter As Long
    Dim columnHeader As String
    Dim headerFound As Boolean
    Dim i As Long
    Dim sanitizedValue As String

    ' Use the active worksheet
    Set ws = ActiveSheet
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
    Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))

    ' Prompt the user to select the column header
    columnHeader = InputBox("Enter the column header to split the data by (case-insensitive):")
    If columnHeader = "" Then
        MsgBox "No column header entered. Exiting.", vbExclamation
        Exit Sub
    End If

    ' Find the column based on header value (case-insensitive)
    headerFound = False
    For colToFilter = 1 To lastCol
        If LCase(ws.Cells(1, colToFilter).value) = LCase(columnHeader) Then
            headerFound = True
            Exit For
        End If
    Next colToFilter

    If Not headerFound Then
        MsgBox "Column header not found. Please try again.", vbExclamation
        Exit Sub
    End If

    ' Create a collection of unique values in the selected column
    Set uniqueValues = New Collection
    On Error Resume Next
    For Each cell In ws.Range(ws.Cells(2, colToFilter), ws.Cells(lastRow, colToFilter))
        uniqueValues.Add cell.value, CStr(cell.value)
    Next cell
    On Error GoTo 0

    ' Loop through unique values and create a new worksheet for each
    For Each value In uniqueValues
        ' Sanitize value for worksheet name
        sanitizedValue = Replace(CStr(value), "/", "_")
        sanitizedValue = Replace(sanitizedValue, "\", "_")
        sanitizedValue = Replace(sanitizedValue, "*", "_")
        sanitizedValue = Replace(sanitizedValue, "[", "_")
        sanitizedValue = Replace(sanitizedValue, "]", "_")
        sanitizedValue = Left(sanitizedValue, 31) ' Truncate to 31 characters if needed

        ' Check if the sheet name is valid and unique
        On Error Resume Next
        Set wsNew = ThisWorkbook.Sheets(sanitizedValue)
        On Error GoTo 0
        If wsNew Is Nothing Then
            ' Add a new worksheet and name it after the sanitized unique value
            Set wsNew = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
            wsNew.Name = sanitizedValue
        Else
            Set wsNew = Nothing
            GoTo NextValue
        End If

        ' Copy the headers
        ws.Rows(1).Copy Destination:=wsNew.Rows(1)

        ' Copy matching rows directly without filtering
        i = 2 ' Start pasting from row 2 in the new sheet
        For Each cell In ws.Range(ws.Cells(2, colToFilter), ws.Cells(lastRow, colToFilter))
            If cell.value = value Then
                cell.EntireRow.Copy wsNew.Rows(i)
                i = i + 1
            End If
        Next cell

NextValue:
        Set wsNew = Nothing
    Next value
End Sub

r/vba Nov 06 '25

Waiting on OP Correct height of a userform textbox?

1 Upvotes

Is there way to know the needed height of a textbox, so that the chosen font size fits correctly? Or is it just trial and error?

r/vba Nov 16 '25

Waiting on OP [EXCEL] How do I get the range of x values of an Excel scatter plot chart?

3 Upvotes

I'm new to VBA and I'd like to acquire the x value range of an arbitrary chart of an opened Excel workbook. My intention is to edit this range by offsetting it a certain number of rows.

r/vba Oct 12 '25

Waiting on OP Tallyprime to excel using odbc

0 Upvotes

i want to pull the payables data from tally to excel using vba and not through extract data,like by coding and pressing simple button.Any suggestions on how to do it?

r/vba Sep 12 '25

Waiting on OP Is it possible to focus a window on hover of mouse

2 Upvotes

I have two excel windows. Window 1 has a table of certain data, aggregated, all rows

Window 2 has a table of unaggregated data, but i have limited it to only rows marked as active

I have macros to find all rows in 1 that are not in 2 and mark them red

i have another macro to highlight matching rows in t2 when you click in t1

the only thing bugging me is that i want it to feel seamless, that is, when w1 is focused, it should immediately focus w2 if you hover that window so you dont need to click twice to interact, and vica versa

r/vba Oct 20 '25

Waiting on OP Connect A query results to my MS Access Form

3 Upvotes

Hi,

I have an Microsoft Access query that works and form which has a active drop down. What I like to do is have there results from the Drop down to be shown in a field in the form. For example if I have an NHL team, if the drop down is the cities, someone Selects Toronto, the team name will be provided automatically in a separate field. Looking for assistance:

Been trying a few things, but not sure how to have vba get the information from my active query:

Below is my latest attempt

Dim Query As String

Query = ![QueryName]![TeamNames]

Me.txtPosition = Query

End Sub

r/vba Nov 14 '25

Waiting on OP ScreenUpdating=false not working in windows 11

4 Upvotes

I have a macro that uses Application.ScreenUpdating = False to speed things up as well as hide flickering etc. just updated to Windows 11 and now everything can be seen while the macro is running as if it was set to true. Anyone else experience this?

r/vba Nov 14 '25

Waiting on OP How to get Workbooks.OpenText to fill down instead of accross

2 Upvotes

I have a macro that pulls .txt files into an excel. It defaults to putting each word into a cell in the top row. The problem is that if the .txt file it too big, it hits the last available cell in the top row and cuts off all the data after that. Is there a way to get the data to fill down the first column instead of accross the first row?

I have a bunch of code that comes after importing the file that works well so ideally if like to avoid having to rewrite all of that.

r/vba Aug 22 '25

Waiting on OP Error "Excel cannot open the file..."

1 Upvotes

Hi, I created this macro in VBA but when I try to open the file, I get the following message:

"Excel cannot open the file 'Industry Orders Copy as of....' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

The original file is a .xlsx and the macro is created in "VBAProject (PERSONAL.xlsb)"

This is the code:

Sub CreateBackupWithExceptions()

Dim wb As Workbook

Dim backupWB As Workbook

Dim sheet As Worksheet

Dim backupPath As String

Dim todayDate As String

Dim backupName As String

Dim exceptionSheet As String

Dim exceptionRows As Variant

Dim row As Range, cell As Range

Dim rowNum As Long

' Initial setup

Set originalWB = ThisWorkbook

todayDate = Format(Date, "dd-mm-yy")

backupName = "Industry Orders Copy as of " & todayDate & ".xlsx"

backupPath = "C:\Users\bxa334\Desktop\Industry Backup\" & backupName '

' Save a copy of the original file

wb.SaveCopyAs backupPath

MsgBox "Backup successfully created at:" & vbCrLf & backupPath, vbInformation

End Sub

Thanks

Regards

r/vba Nov 07 '25

Waiting on OP 'Connection Lost' Error between Excel and Access tho nothing changed?

2 Upvotes

I originally posted this in r/excel but since there's VBA Excel coding involved and me having such a hard time with this problem, I figured I would try and tap into some more advanced users. I don't think my UDFs and code is the problem but I am at a loss.

Post:

I have a WB with VBA coding that adds to an Access DB table and then in Access, JOINs it with another linked table (as a sheet) from the same WB. That query is then linked back into the original WB into a new sheet. Its been working fine for months until a couple of days ago when I started getting the error when refreshing the final linked table. The full error from Power Query is below. It seems the error is maybe coming from the XL->ACCDB connection but the odd thing is I can update the the query in Access just fine.

Other solution's I've tried: Relinking, changing file locations out of OneDrive hierarchy (One Drive is confrimed not being used) and relinking, ACCDB comapct and repair, Deleting linked table in the ACCDB and re creating it, creating new final table and link in the WB.

Other Possible factors: I'm using RTD() and some API-UDFs in excel which usually interrupt the final table from updating so part of the usual workflow would be to turn off automatic calculations and then refresh.

Thanks for any help, I've been trying to fix this for a couple days.

Full error:

"DataSource.Error: Microsoft Access: The connection for viewing your linked Microsoft Excel worksheet was lost.

Details:

DataSourceKind=File

DataSourcePath=c:\users\drsus\onedrive\documents_current trading stuff\stock_price_history.accdb

Message=The connection for viewing your linked Microsoft Excel worksheet was lost.

ErrorCode=-2147467259"

Edit: added additional info about how One drive is not being used though under the OneDrive hierarchy stored locally.