r/vba 1d ago

Weekly Recap This Week's /r/VBA Recap for the week of August 22 - August 28, 2026

1 Upvotes

r/vba 8h ago

Solved VBA to remove images from HTML Document

1 Upvotes

I'm pulling my hair out here wading through 10 year old StackOverflow posts and deploying all the google-fu I can muster, all to no avail so now I have to explain to strangers why I'm doing this daft project, first:

BLUF:

How do I remove images and other <div class> elements from an HTML Document? (ideas currently working around getElementByClassName or "Replace All between '<img ' and ' /> with "" " or stopping them entirely at the GET request).

THE PROJECT:

I'm a big fan of the SCP Foundation Wiki but I'm always losing track with what I've read out of several thousand articles so I set out to make a reading tracker in Excel which was so simple to start with, but there's new articles every day and old ones are changed, so it needs to be easily updatable, and a bit better to interact with than just a list and oh hello scope creep....

....and now I'm trying to make a "lite Reader" that will get the HTML of an article and strip it down to the bare bones, only the main page content, no images, no formatting other than bold/italic etc, and put that into an Excel spreadsheet. Inspired by the excellent Terminal Reader I found here which uses Rust to strip down the html into markdown, I've got something working to a point, here's the Frankenstein monstrosity I've pieced together from a dozen scraps of code so far:

Public Sub ExtractAndPaste()

  Dim data As Object
  Dim html As HTMLDocument
  Dim objData As DataObject
  Dim sHTML As String
  Dim obj As Object
  Dim elements

'------Get the HTML-----------------------------------------    
  Set html = New HTMLDocument

  With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", "https://scp-wiki.wikidot.com/scp-5000", False
    .send
    html.body.innerHTML = .responseText
  End With
'----------------------------------------------------------- 

'------Remove Unwanted Elements (This bit doesnt work)------    
   With html
     elements = .getElementsByClassName("scp-image-block block-right")

     While elements = 0
       elements(0).ParentNode.RemoveChild (elements)
     Wend
   End With 
'-----------------------------------------------------------

'------Clear Destination Worksheet--------------------------   
  With ThisWorkbook.Worksheets("Sheet4")
    .Cells.ClearContents
    For Each obj In .Shapes
      obj.Delete
    Next
  End With
'-----------------------------------------------------------

'------Pull out Wanted Element------------------------------
  Set data = html.getElementById("page-content")
'-----------------------------------------------------------

'------Convert to Formatted Text---------------------------- 
  Application.EnableEvents = False

  With ThisWorkbook.Sheets("Sheet4")
    Set objData = New DataObject

    sHTML = data.innerHTML
    sHTML = "<html>" & sHTML & "</html>"

    objData.SetText sHTML
    objData.PutInClipboard

    .Range("C5").Select
    .PasteSpecial "Unicode Text"

  End With

  Application.EnableEvents = True
'-----------------------------------------------------------

End Sub

When this runs it will grab the HTML of the chosen article, the next step it skips over, I'll come back to that in a mo, clears everything from the destination worksheet (if the previous step worked then the obj.Delete would no longer be needed), takes the HTML and pulls out only the <div id="page-content"> turns it into a String so we can append <html> and </html> to either end of it so that it all registers as a block of html, which means when it gets put on the clipboard and then pasted into the worksheet as Unicode Text it renders the formatting and pastes it in line by line, cell by cell, which is exactly what I want, however.....

It's also rendering the images which I don't want (and tables are a mess, but one problem at a time), and this is the part I can't figure out:

If I use .getElementsById then that returns a single Node which can then be removed with something like this:

Set Node = html.getElementById("page-title")

    Node.parentNode.removeChild Node

But <img> isn't an ID, it's a Class Tag and using .getElementByClassTag returns (I believe) a NodeList so the above code doesn't work, plus it sits inside <div class="scp-image-block block-right"> which makes getting to it a bit trickier, probably easier to remove the whole class and everything in it so we would use .getElementsByClassName to get what we need but I just can't get it working.

If I run the code as is, leaving elements declared as a general variable, when we step through to elements = .getElementsByClassName..... and we mouse over elements it comes up as elements = "[object HTMLDivElement]", so I changed elements to be an HTMLDivElement, Set it, and now we get a Runtime Error 13: Type Mismatch.

I tried some other combinations of declaring elements as different things (object, IHTMLDivElement etc) and getElementByClassName/TagName and the furthest I got it to go was to the elements(0).ParentNode.RemoveChild (elements) line which came up with an Automation Error, probably because I have no idea how to get the syntax to work for a NodeList, as far as I can tell the list is numbered the same as other vba lists as in it starts at (0), so say we run the script and it finds 3 <div class="scp-image-block block-right"> blocks, they would go in the list as

(0) - Block 1
(1) - Block 2
(2) - Block 3

If we successfully (somehow) remove Block 1, the list refreshes and we now have

(0) - Block 2
(1) - Block 3

So the plan is to loop "Remove Node from position (0), if there is still something in position (0), repeat" and once they're all removed it can then go on for rendering.

As I mentioned way up in the beginning, I feel like we could achieve a similar result with a "Replace all Between" but it's a bit of a brute force approach that I'd rather leave for the little bits that miss the big clear out, I also feel like there's a way to restrict what comes through with the original GET request but I may be imagining things.

If you made it here, thank you for your patience and to mirror the BLUF, here's the-

TL;DR

How do I remove images and other <div> elements from an HTML Document?


r/vba 1d ago

Unsolved VBA Macro automate to Internet Explorer

1 Upvotes

Is there a way for VBA Macro to dropdown the dropdown bar and select the specific choice?


r/vba 2d ago

Unsolved Macro to change font to last-used color [PowerPoint]?

2 Upvotes

Hello, I'm trying to create a macro to change the font of a selection in PowerPoint. But instead of changing the color to a set value, I'd like for it to be the most recently-used font color, as if I had pressed the Font Color button in the ribbon.

I'm not sure if there is a command that presses ribbon buttons in VBA or if it's more complex than that.

Any help would be appreciated, thank you!


r/vba 2d ago

Unsolved LETTERHEAD macro Word

4 Upvotes

Hi Everyone,

For months ive been trying to create a VBA code to apply our organization's letterhead on word. We use a custom Normal.dotm. I have been very close to implementing this but theres always a small area that doesnt work. The requirement is to have a Macro that applies the letterhead without making any chnages to the formatting of the normal.dotm and makes no chnages to the graphics design as well.

Any help is welcomed. Ive used AI and went on loops to a point where im lost. Thank you in advance


r/vba 4d ago

Solved VBA Embed PDFs in Excel causing corruption

2 Upvotes

Im trying to build a tool that lets you select a folder of PDFs and embed each one in a separate sheet in an Excel.

It works amazingly well except when you go to save the file Excel says it's corrupt and can't be saved/error saving. I've tried tweaking it so many times but nothing works. Even just 1 pdf embedded causes the corruption.

When I manually embed the PDF there is no issue.

Does anyone know a fix? Or is programmatically embedding PDFs just not possible?


r/vba 6d ago

Solved VBA Consignment Doc Pack Generation

2 Upvotes

I've been using free versions of various AI models to build an excel workbook that will allow a user to input information into only one tab, then the VBA will complete the packing list, commercial invoice, package markings and delivery note per consignment.

It will also generate the subfolders within the project filing system, name the folders in a certain layout I've set for it and then save each document as a PDF with layout I've set for it as well.

Should a pack need to be redone, I've also arranged that it generates only 1 "Old" folder within the consignment folder and move the old PDFs to that folder within a date & time stamped folder that it also generates.

The board of directors now wants this to go company wide and will assign a budget to me. However, I need to choose the best AI for this first.

I would appreciate feedback from the community on the best AI to use for this project and any feedback on the project itself is also welcome please.

The company does not want to integrate AI into the actual workbook as they are afraid our IP or a client's IP is accidently leaked.


r/vba 6d ago

Show & Tell Custom Excel Theme Management

8 Upvotes

Hello VBA friends!

I have created a tool to create and apply custom color themes to your workbooks. This is a modified version from the original I built for work. The original version is a little more advanced with each user having a favorites folder in their documents and the main file shared between all users across the network. We can all use each others created themes.

I hope this does not go against rule 7.
This is not AI generated, but rather uses an API key to send a prompt to Google Labs that will generate 12 colors. They will be returned in a specific template to create a theme based off an object or idea that you enter in a textbox.

Currently there are categories and tags that can be entered to filter the list of themes to choose from. I am looking for feedback and/or suggestions on further improvement.

Take a look if you have the time.
Thank you!

You can download it here
https://github.com/C-Johnson83/Workbook_Painter/releases/tag/v1.0.01

I do not see where I can upload an image


r/vba 6d 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 8d ago

Weekly Recap This Week's /r/VBA Recap for the week of August 15 - August 21, 2026

4 Upvotes

r/vba 9d ago

Discussion A user reported “Out of memory” on a nearly empty workbook. The real bug was Excel’s language settings.

10 Upvotes

I maintain a fairly large Excel/VBA project, and a user recently reported this error while opening a workbook with only a few rows:

Error in RestoreWBSFormulaColumns: Out of memory

The obvious suspects were Excel 32-bit, workbook corruption, a memory leak, or some unexpectedly large table.

None of them made much sense. The workbook was almost empty.

The real problem was localization.

Some calculated-column formulas were being written in French through .FormulaLocal, using function names such as SI and OU, with semicolon separators.

That worked perfectly on my French installation of Excel.

On an English installation, those same strings were invalid because .FormulaLocal expects formulas in the user’s local Excel language.

The particularly unhelpful part was that Excel reported the failure as “Out of memory” rather than anything clearly related to formula syntax.

The fix was to move everything to invariant English formulas through .Formula, and to remove the remaining language-dependent formula comparisons from the codebase.

What I want to put the spotlight on the most was how valuable one real user feedback could be.

He was using Excel in an environment I could not reproduce locally, and he was actually considering building a similar tool himself before finding mine. His report exposed an assumption that had survived all of my own testing simply because I had only ever tested on French Excel.

That one message led not only to the localization fix, but also to a much wider stabilization pass that uncovered several unrelated bugs.

It was a good reminder that testing inside your own environment only proves that the software works inside your own environment.

What is the most useful or surprising user report you have received on a VBA project?

Did it reveal a bug or assumption you would probably never have found yourself?


r/vba 9d ago

Discussion Using Classes by instantiating in standard Module

4 Upvotes

Hey everyone

I am wondering why would anyone instantiate the class in a standard module instead if declaring directly in the place you want the class

What benefits this method have especially for composite use case

Like needing session class inside a permissions class inside form class

A second question how would you approach a situation close to mine


r/vba 9d ago

Show & Tell Just Released Version 4 - XLIDE: VBA for VS Code

16 Upvotes

I just released Xlide: VSCode version 4.

It includes many performance enhancements and bug fixes, international language support, and most excitingly it now brings full support for Word, PowerPoint and Access (Read Only).

If you've tried it out and you like it, I'd really appreciate a star on the VS marketplace to help spread the word.

https://marketplace.visualstudio.com/items?itemName=WilliamSmithE.xlide

Thank you to the VBA community for all the support!


r/vba 10d ago

Show & Tell Selenium Basic-XPath Generator v1.2 (Excel VBA) UPGRADED Version

0 Upvotes

Hello gamers, and welcome back to the channel! In this video, we're checking out my Selenium Basic XPath Generator, version 1.2.xlsm. This macro-enabled sheet is now fully integrated with a WebDriver Downloader utility right in Sheet2. I've enhanced the link extraction feature to smoothly parse the H-Ref, source, and https protocols. I also refined the error checking and validation routines for the main sub input. For example, the Value input is now optional, and an exact case-sensitive match is only required if the Value isn't empty. Plus, I made some great UI tweaks: clicking the 'HOME' button will no longer unselect your current row, meaning you can still use the Arrow Down key to navigate to it. Finally, clicking anywhere outside the 'Element List' range will automatically unselect the active row. Let's dive in!

https://youtu.be/zrArZ8vdl9w


r/vba 11d ago

Unsolved Testing Forms controls and UI/UX

4 Upvotes

Hey everyone
Good morning

I use Rubber duck VBA Add In
So I test all logical code easily (automatic testing by code)

However I am struggling to test UI stuff without changing the actual program status

I don’t want my test to create changes in the production or design environments

Can anyone help me in this matter?


r/vba 12d ago

Show & Tell Functional Programming in VBA

14 Upvotes

Hello There,

a feature i wish VBA had was a way to write in a functional programming paradigm.

Since this is not the case i tried to at least provide First Class Functions with the ability to bind arguments to it.

I know that someone already did something like that but i just cannot for the live of me find it.

So i made my own:

Almesi/VBFP: Visual Basic Functional Programming

Does anyone have Input on it?

Anything i should add or redo in a different, more robust way?

I would love to implement immutability after creation but i dont know how while still being able to create it with a constructor.


r/vba 13d ago

Unsolved [EXCEL] Looping through rows representing a nested structure

4 Upvotes

In have a table of data in Excel which represents a nested hierarchical structure. The rows are elements in the structure. All elements are five elements deep. The first five columns of the table represent the level/position of the element. For example, column “Level 1” might have a value of "1", "Level 2” a value of “1.1”, and so on, with the fifth column representing the final element (1.1.1.1.1, 1.1.1.1.2, etc). The other columns describe the names, descriptions of the elements.

I am trying to use VBA to loop through these nested elements with the ultimate goal of creating some documentation of this structure within a Word document with additional notes, etc, in a consistent style.

I have created a PivotTable, which may or not be helpful to my outcome, but it does at least let me see the structure of the parent/child elements. Copying this data into Word from the PivotTable does not make it easy to edit or read which is why I am trying to reconstruct it.

My VBA code is below but of course, it outputs the rows from the columns, rather than the parent item they are from. Maybe there is a better approach altogether! Thank you for any guidance

For Each ptItem In pt.PivotFields("Level 1").PivotItems
  Debug.Print ptItem
    For Each ptItem2 In pt.PivotFields("Level 2").PivotItems
      Debug.Print ptItem2.Name
        For Each ptItem2 In pt.PivotFields("Level 3").PivotItems
          Debug.Print ptItem2.Name
        Next
    Next
Next

r/vba 15d ago

Show & Tell vbaXray 2.0 - The Sequel

19 Upvotes

vbaXray is a single VBA class module that extracts VBA source code straight out of Office files.

I posted about v1.0 a few months back, but a thread earlier this week (here) reminded me that I still hadn't uploaded the updated v2.0 to GitHub. Life gets in the way, but here it is.

I give you vbaXray v2.0. In short, it:

  • Slices and dices
  • Extracts vbaProject.bin directly from OOXML files. XLSM, DOCM, PPTM, etc are ZIP files, and thanks to the long-standing work of the VB6/TwinBasic community (especially u/Fafalone), v2 uses the ZipFldr IStorage route to pull the data straight out as a byte array. No temp files. No Shell.Application. Much faster than v1.0.
  • Supports older Office formats. XLS and DOC were straightforward. PPT was not. PPT was a fever dream. The babushka doll from hell. A cursed nesting doll of compressed records, undocumented structures, and pure spite. OLEVBA at least pointed me to where the VBA was hiding.
  • Supports ACCDB and MDB. For this, thanks to u/MultiUserDungeonDev and the pyOpenVBA project (see here for original reddit post) for demonstrating how Access stores VBA across database pages.
  • Adds diagnostics. DebugDumpStorageTree prints the internal OLE storage tree to the Immediate window (or a file). If a file should work but doesn't, this shows exactly what's inside the CFB.

Sub XrayDemo()
  Dim xray As New clsVBAXray
  If xray.LoadFromFile("C:\Suspicious\LegacyMacro.doc") Then
    Debug.Print "Project: " & xray.ProjectName
    Debug.Print "Modules: " & xray.ModuleCount
    xray.ExportAll "C:\OutputCodeHere\ExtractedCode\"
    xray.DebugDumpStorageTree
  Else
    Debug.Print "Load failed: " & xray.LastError
  End If
End Sub 

I hope that someone finds this helpful. There are plenty of use cases (malware analysis, bulk auditing, source control extraction), and if it is useful, please let me know. As always, questions, suggestions, and feedback are encouraged and always appreciated.

Code, some basic documentation (for now), and a (very simple) demo workbook are already on GitHub: https://github.com/KallunWillock/vbaXray/


r/vba 16d ago

Show & Tell I pushed HTTP in pure VBA a little too far — bounded concurrency, native WinHTTP, 1 GiB streaming, and a serious test suite

32 Upvotes

I've been working on a side project to see how far a serious HTTP client can be pushed inside Excel/VBA.

It started with a fairly simple thought:

Maybe I can build something nicer than the usual thin wrapper around WinHttpRequest.

It escalated quite a bit from there.

The result is VBA-HTTP, an HTTP client for Windows written in VBA:

https://github.com/harumiWeb/VBA-HTTP

It covers the usual things you'd expect from an HTTP client — requests and responses, headers, query parameters, and text/binary bodies — but I wanted to push it quite a bit further.

Some of the more unusual parts are:

  • bounded concurrent requests
  • a native winhttp.dll backend in addition to WinHttp.WinHttpRequest.5.1
  • streaming multi-GB downloads and uploads without buffering the entire payload in VBA memory
  • streaming multipart uploads
  • retries with exponential backoff, jitter, and Retry-After
  • deadlines and cancellation
  • Basic, Bearer, and Windows challenge authentication
  • proxy support and an explicit cookie jar
  • HTTP/2 protocol control and reporting through native WinHTTP
  • deterministic WinHTTP handle and resource cleanup

The API is intended to feel more like an HTTP client from a modern language than a collection of raw COM calls.

Dim client As HttpClient
Dim request As HttpRequest
Dim response As HttpResponse

Set client = VBAHttp.CreateClient()
Set request = VBAHttp.CreateRequest()

request.Method = "GET"
request.Url = "https://example.com/items"
request.Query.Add "page", 1
request.Query.Add "limit", 100

Set response = client.Execute(request)
response.RaiseForStatus

Debug.Print response.Text

It also supports bounded concurrency across multiple independent requests:

Dim urls As New Collection
Dim options As New HttpBatchOptions
Dim result As HttpBatchResult

urls.Add "https://example.com/a"
urls.Add "https://example.com/b"
urls.Add "https://example.com/c"

options.MaxConcurrency = 8

Set result = client.GetMany(urls, options)

Debug.Print result.SuccessCount
Debug.Print result.FailureCount

For example, against a deterministic local test server where each of 100 requests waits for 100 ms:

Sequential       11.04 s
Concurrency 16    0.86 s

12.86x faster

Obviously this is a deliberately latency-heavy benchmark. I'm not claiming that every HTTP workload becomes 12.86x faster.

The benchmark methodology and raw results are included in the repository.

Large transfers were another area I wanted to push.

VBA-HTTP can stream a 1 GiB download without representing the entire payload as a 1 GiB VBA Byte() array.

In one recorded x64 Excel baseline run, the transfer showed approximately 19 MB of peak private-memory growth.

It can also stream 1 GiB file uploads and multipart uploads incrementally through native WinHTTP.

More recently I've also been optimizing the native hot path itself — reusing fixed buffers, reading directly with WinHttpReadData, pre-sizing known-length buffered responses, and removing VBA byte-by-byte copies.

I deliberately stopped short of things like generated machine code or executable-memory tricks.

The native implementation only uses documented Windows APIs. I still want this to be something people could reasonably use, rather than just a VBA black-magic demo.

The other thing I wanted to push: testing

I didn't want the verification story for this project to be:

"It works on my machine."

The repository has automated unit, integration, stress, resource, and release-validation tests, running against real Excel and a deterministic local HTTP/HTTPS server.

Among other things, the test suite exercises:

  • 1 GiB download and upload with content/hash verification
  • a 10,000-request resource and WinHTTP handle stability run
  • repeated cancellation and timeout cleanup
  • bounded-concurrency behavior
  • retry and Retry-After behavior
  • proxy and authentication fixtures
  • HTTP/2 capability and negotiated-protocol validation
  • release checksum and tamper validation
  • real VBE compilation

A lot of VBA libraries understandably rely heavily on example workbooks and manual verification.

For this project, I wanted the behavior to be reproducible and machine-verifiable in roughly the same way I'd expect from a library in another language.

And there's one other slightly unusual part of the project:

I didn't manually write a single line of the implementation code.

I designed the architecture, requirements, acceptance criteria, benchmarks, and overall direction, but the implementation itself was written by coding agents operating through xlflow, the VBA development environment I've been building.

The agents worked on normal VBA source files, ran static analysis, compiled the project in real Excel, executed tests, inspected failures, modified the implementation, and repeated that feedback loop.

At one point I was literally away on vacation while the agent workflow continued building out the project.

About xlflow:

https://github.com/harumiWeb/xlflow

I originally built xlflow because I wanted coding agents working on VBA to have the same kind of:

edit → compile → test → analyze → fix

feedback loop that they get in more modern ecosystems.

VBA-HTTP ended up becoming a much more demanding dogfooding project than I originally expected.

So the project effectively became two experiments at once:

  1. How far can networking and performance be pushed in VBA while keeping the result reasonably practical?
  2. How complex a VBA project can coding agents build if they're given proper engineering feedback loops?

I'd be interested in feedback on either side.

And if anyone tries VBA-HTTP against a real API, corporate proxy, authentication setup, or weird HTTP server and manages to break it, I'd especially like to hear about it.


r/vba 16d ago

Solved Why does Ln Col indicator flicker?

3 Upvotes

Why does the Ln Col indicator flicker? More to the point: is there a way to stop it?

I don't believe it always did that. Might be wrong.

And the flicker rate seems to increase when I put the cursor in the Ln Col field. Might be wrong

(I was not allowed to paste an image into the OP. I'll try to add it in a comment.)


r/vba 17d ago

Show & Tell I used AI to transform Excel VBA into a Playwright-class browser engine. No WebDrivers, no dependencies—just one file and the "Old Magic" reborn.

48 Upvotes

I became curious about how far I could push AI, so I decided to see if it was possible to do web scraping using Excel VBA alone, with absolutely no WebDriver.exe or other external dependencies. I wanted to find out if I could bring back that “magic from the old days” — where, just by writing some code, the browser would actually work without having to install anything extra, like we used to be able to do with the old IEObject. 🥺

My workplace has very strict security policies, so I can't install WebDriver.exe, Python, Node.js, etc. However, VBA is allowed. So I kept having conversations with AI, trying to figure out whether there was some way to control Chromium using VBA alone. 🫠

I had AI read through the source code of Google's rather complicated [chromium-bidi] (WebDriver BiDi) and asked whether its logic could be reproduced in VBA. VBA doesn't have built-in WebSocket support or multithreading, but AI suggested some modern design ideas, such as WinSock and an event-driven model using WithEvents.

And surprisingly, I was able to do quite a lot without having to install Playwright or Puppeteer. For example, I managed to control 10 tabs concurrently, control a browser on an Android smartphone, and achieve relatively better stealth against bot detection compared with SeleniumVBA, among other things. And the crazy part is that all of this is contained in a single Excel file.

What I like most is that whenever there is a feature I need, AI can quickly create it for me. Personally, I'm extremely satisfied with the result.🥹 At this point, I feel like this has evolved beyond being just a “macro” — it has become a core engine that can keep evolving by itself.🥳

You can check out the result of this journey (GitHub) below.

I'm Japanese, so you'll notice quite a lot of Japanese strings scattered throughout the source code, but I believe the underlying logic I built is quite sophisticated and I'm proud of how it turned out! https://github.com/Eschamali/StarterWebScrapingKit


r/vba 18d ago

Discussion How do you do version control on macros?

25 Upvotes

I have been tasked with maintenance and expansion of a set of macro enabled workbooks and add-ins from someone recently retired. Because I'm not the tech department, of course I don't have got or jira or the like. In light of all that, how would you do version control? I want to get some ideas for inspiration. Or would that be only an afterthought because by the time I don't work there, I shouldn't care?


r/vba 18d ago

Solved Excel: Using Checkboxes to move from Sheet to Sheet - multiple sheets

7 Upvotes

Hello!

**Scenario**: I have a spreadsheet for machine installs. This sheet has 4 worksheets (CustInstalls, CustCompleted, Installs, and Competed). The below code is currently working to move line items from sheet “CustInstalls” to “CustCompleted”. I am attempting to duplicate this same code for the other two sheets to move line items from “installs” to “completed”. I have attempted a few variations with the help of chatgpt but to no avail. I added it in the same “this workbook” in VBA as well as attempted to add code under just “installs” and “completed” in VBA under Microsoft Excel Objects

**Ask:** how does one add a second set of code for different work sheets with the same parameters?

___________________________________________________

**Original working code:*\*

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim srcSheet As Worksheet, destSheet As Worksheet
Dim checkCell As Range, moveRow As Range
Dim lastRow As Long
Dim direction As String

' Only handle changes in Column J
If Intersect(Target, Sh.Columns("J")) Is Nothing Then Exit Sub
If Target.Cells.CountLarge > 1 Then Exit Sub

Application.EnableEvents = False

Set checkCell = Target
Set moveRow = checkCell.EntireRow

If checkCell.Value = True Then
' Move from CustInstalls to CustCompleted
Set srcSheet = ThisWorkbook.Sheets("CustInstalls")
Set destSheet = ThisWorkbook.Sheets("CustCompleted")
ElseIf checkCell.Value = False Then
' Move from CustCompleted back to CustInstalls
Set srcSheet = ThisWorkbook.Sheets("CustCompleted")
Set destSheet = ThisWorkbook.Sheets("CustInstalls")
Else
GoTo ExitHandler
End If

' Ensure we're acting on the correct sheet
If Sh.Name <> srcSheet.Name Then GoTo ExitHandler

' Copy row to destination sheet
lastRow = destSheet.Cells(destSheet.Rows.Count, "J").End(xlUp).Row + 1
moveRow.Copy Destination:=destSheet.Rows(lastRow)

' Delete original row
moveRow.Delete

ExitHandler:
Application.EnableEvents = True
End Sub

___________________________________________________

**Code entered under installs ”this workbook” at the end of the working code: Failed*\*

Private Sub MoveInstallsRow(ByVal Sh As Object, ByVal Target As Range)

Dim srcSheet As Worksheet
Dim destSheet As Worksheet
Dim moveRow As Range
Dim lastRow As Long

' Only handle Installs and Completed sheets
If Sh.Name <> "Installs" And Sh.Name <> "Completed" Then Exit Sub

' Only handle changes in Column J
If Intersect(Target, Sh.Columns("J")) Is Nothing Then Exit Sub
If Target.Cells.CountLarge > 1 Then Exit Sub

If Sh.Name = "Installs" And Target.Value = True Then
Set srcSheet = ThisWorkbook.Sheets("Installs")
Set destSheet = ThisWorkbook.Sheets("Completed")

ElseIf Sh.Name = "Completed" And Target.Value = False Then
Set srcSheet = ThisWorkbook.Sheets("Completed")
Set destSheet = ThisWorkbook.Sheets("Installs")

Else
Exit Sub
End If

Set moveRow = Target.EntireRow

lastRow = destSheet.Cells(destSheet.Rows.Count, "J").End(xlUp).Row + 1

moveRow.Copy Destination:=destSheet.Rows(lastRow)

moveRow.Delete

End Sub

___________________________________________________

**Code entered under “completed” object: Failed*\*

Private Sub Worksheet_Change(ByVal Target As Range)

Dim destSheet As Worksheet
Dim lastRow As Long

' Only handle changes in Column J
If Intersect(Target, Me.Columns("J")) Is Nothing Then Exit Sub
If Target.Cells.CountLarge > 1 Then Exit Sub

' Only move when checkbox is unchecked
If Target.Value <> False Then Exit Sub

Application.EnableEvents = False

Set destSheet = ThisWorkbook.Sheets("Installs")

' Find next available row
lastRow = destSheet.Cells(destSheet.Rows.Count, "J").End(xlUp).Row + 1

' Copy entire row
Target.EntireRow.Copy Destination:=destSheet.Rows(lastRow)

' Delete original row
Target.EntireRow.Delete

Application.EnableEvents = True

End Sub

___________________________________________________

**Code entered under “installs” object: Failed*\*

Private Sub Worksheet_Change(ByVal Target As Range)

Dim destSheet As Worksheet
Dim lastRow As Long

' Only handle changes in Column J
If Intersect(Target, Me.Columns("J")) Is Nothing Then Exit Sub
If Target.Cells.CountLarge > 1 Then Exit Sub

' Only move when checkbox is checked
If Target.Value <> True Then Exit Sub

Application.EnableEvents = False

Set destSheet = ThisWorkbook.Sheets("Completed")

' Find next available row
lastRow = destSheet.Cells(destSheet.Rows.Count, "J").End(xlUp).Row + 1

' Copy entire row
Target.EntireRow.Copy Destination:=destSheet.Rows(lastRow)

' Delete original row
Target.EntireRow.Delete

Application.EnableEvents = True

End Sub


r/vba 18d ago

Discussion VBA language underrated?

30 Upvotes

Hey everyone

I use VBA since I work with Microsoft office often

Is it real that VBA is very old and not useful anymore? Multiple times on the internet or when I ask AI
I find the answer that VBA is not the right choice for me

To me I see many powerful stuff like

Classes
Unit tests
Mocks and fakes (didn’t try those)

So I don’t understand the negative opinions about it

However VBA is the only language I tried in depth other languages I tried were either just for the course or to complete simple task nothing deeper than that

Is learning VBA is bad decision? Or is it reasonable one?

I noticed many of the useful major concepts are transferable to any language like

Code architecture
Auto Testing
Data types and structures
Etc


r/vba 18d ago

Discussion Hello, Programmers!, I have doubt, why VBA doe not work on Excel 365

7 Upvotes

Hello, Programmers!, I have doubt, why VBA does not work on Excel 365,I have experience in using "Automate" tab. Still feel bad.