Excel VBA not showing userform - vba

I have a VBA macro that opens by asking the user a series of questions (asking them to say which of the open workbooks performs which function). I have a series of userform.show commands as below:
UserForm2.Show ' select cost data file
Set piersBook = ActiveWorkbook
UserForm5.Show ' select IRR file
Set irrBook = ActiveWorkbook
UserForm6.Show ' select BC summary file
Set bcSummary = ActiveWorkbook
(now, after the event, I realise it would have been more simple to put these into one userform).
The net effect is for the last one not to display.
After some research I changed the code to:
UserForm2.Show ' select cost data file
Set piersBook = ActiveWorkbook
UserForm5.Show ' select IRR file
Set irrBook = ActiveWorkbook
DoEvents
UserForm6.Show ' select BC summary file
Set bcSummary = ActiveWorkbook
This worked for about 5 or 6 iterations, before it reverted to the original problem.
I put breakpoints in the userform initialize code. They were all called and the userforms all worked (until I removed the breakpoints again).
Finally I started removing the offending userform: the problem transfered itself to the next one back. And again, when that was removed, to the one before.
The userforms' code is identical:
Private Sub ListBox1_Click()
Workbooks(ListBox1.Value).Activate
Unload Me
End Sub
Private Sub UserForm_Initialize()
Dim wb As Workbook
For Each wb In Workbooks
ListBox1.AddItem wb.Name
Next wb
End Sub
Any thoughts? At the moment I am hardcoding the inputs which is not ideal.
Many thanks.

use only UserForm2, then:
change your UserForm2 code as follows
Private Sub ListBox1_Click()
With Me
If ListBox1.ListIndex <> -1 Then
.Tag = .ListBox1.Value
.Hide
Else
MsgBox "You must select a workbook"
End If
End With
End Sub
Private Sub UserForm_Initialize()
Dim wb As Workbook
For Each wb In Workbooks
ListBox1.AddItem wb.Name
Next wb
End Sub
change your "main" code as follows
Dim piersBook As Workbook, irrBook As Workbook, bcSummary As Workbook
With UserForm2
.Caption = "select cost data file"
.Show ' select cost data file
Set piersBook = Workbooks(.Tag)
.Caption = "select IRR file"
.Show ' select cost data file
Set irrBook = Workbooks(.Tag)
.Caption = "select BC summary file"
.Show ' select BC summary file
Set bcSummary = Workbooks(.Tag)
End With
Unload UserForm2

Related

What code to use in copying the workbook, removing all macros (including form controls), and pasting to another New Workbook w/o removing formula?

I created a workbook that is automated with macro and I want to copy the whole workbook and paste it into another workbook and remove all macro's (including the form controls) except only the formulas.
My code is working copying the workbook and pasting to another workbook (including the formulas) and removing the macros. But the Form controls were still keep on appearing in the new workbook. What code do I need to add? Please help me. My code is written below:
Private Sub Label16_Click()
Unload Me
Dim NewWkb As Workbook
Dim xWkb As Workbook
Dim x As Integer
Set xWkb = Workbooks("Technical Support Database (Automated by MACRO).xlsb")
Set NewWkb = Workbooks.Add
NewWkb.SaveAs "C:\Users\TSJeddah\OneDrive - Delta Marketing Co\JIM FILES\Operation Files\" & "TS Database (No MACRO).xlsx"
For x = 1 To xWkb.Worksheets.Count - 1
xWkb.Sheets(x).Copy after:=NewWkb.Worksheets(NewWkb.Worksheets.Count)
Next x
End Sub
If you need to remove all form controls from the target workbook, you can do so with the following code:
Sub DeleteFormControlsFromWB(WB As Workbook)
Dim sh As Shape, ws As Worksheet
For Each ws In WB.Worksheets
For Each sh In ws.Shapes
If sh.Type = msoFormControl Or sh.Type = msoOLEControlObject Then
Debug.Print "Deleted Form control: " & sh.Name 'debug
sh.Delete
End If
Next
Next
End Sub
Sub UsageExample()
DeleteFormControlsFromWB ThisWorkbook
End Sub
Private Sub Label16_Click()
Unload Me
Dim NewWkb As Workbook
Dim xWkb As Workbook
Dim x As Integer
Set xWkb = Workbooks("Technical Support Database (Automated by
MACRO).xlsb")
Set NewWkb = Workbooks.Add
NewWkb.SaveAs "C:\Users\TSJeddah\Desktop\JIM\" & "TS Database (No
MACRO).xlsx"
Call UsageExample
For x = 1 To xWkb.Worksheets.Count - 1
xWkb.Sheets(x).Copy
after:=NewWkb.Worksheets(NewWkb.Worksheets.Count)
Next x
ActiveWorkbook.Close
Application.ScreenUpdating = True
End Sub

Automatically open an excel file to cell A1 in all worksheets (using VBA)

I am trying to write VBA code so that whenever I open any file in excel, it automatically goes to Cell A1 in all sheets (no matter what cells were selected when it was last saved). I found something online that suggested putting the following code in my Personal .xlsb project:
Sub kTest()
Dim i As Long, s() As String, a As String, n As Long
With ActiveWorkbook
For i = 1 To .Worksheets.Count
a = a & .Worksheets(i).Name
n = n + 1
ReDim Preserve s(1 To n)
s(n) = .Worksheets(i).Name
If Len(a) > 224 Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
n = 0: a = "": Erase s
End If
Next
If Len(a) Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
End If
Application.Goto .Worksheets(1).Range("a1")
End With
End Sub
But nothing happens when I open a file. Please help!
You cannot go to Cell A1 in every sheet. But if you would like to go to Cell A1 of a single sheet you could do the following.
Create a class ExcelEvents with the following code
Option Explicit
Private WithEvents App As Application
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
App.Goto Wb.Worksheets(1).Range("A1")
End Sub
Private Sub Class_Initialize()
Set App = Application
End Sub
And in ThisWorkbook add
Option Explicit
Private xlApp As ExcelEvents
Private Sub Workbook_Open()
Set xlApp = New ExcelEvents
End Sub
Save the workbook, re-open it and the code in the workbook_open event will run and that means as soon as you open another workbook the code will goto cell A1 of sheet 1
EDIT If you really mean to select A1 in every single sheet you could change the code as follows
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
Dim sh As Worksheet
App.ScreenUpdating = False
For Each sh In Wb.Worksheets
sh.Select
sh.Range("A1").Select
Next
App.Goto Wb.Worksheets(1).Range("A1")
App.ScreenUpdating = True
End Sub
A simple solution:
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
Using MicScoPau's loop through the worksheets
Place the following code in the ThisWorkbook module of Personal.xlsb:
You'll have to reopen excel for this to work the first time.
If your Personal.xlsb is hidden, then you will have some issues with the each sheet in activeworkbook.
Private WithEvents app As Application
Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
End Sub
Private Sub Workbook_Open()
Set app = Application
End Sub

VBA other Workbook Doesnt close Properly

Hi there My VBA code does not want to close my Raw data File properly.
I have a data capture form then , When I hit Submit, Opens another Excel File, Copies all the data into it and is supposed to save and close the workbook.
My code is as follows:
Private Sub submit_Click()
'Open Workbook
If MsgBox("You are about to Submit, Are you sure?" & vbCr & "Please make sure that the OUTCOME box is complete", vbYesNo) = vbNo Then Exit Sub
Dim wb As Workbook, sh As Worksheet
Set wkb = Workbooks.Open("\\ServerName\Reports Folder\Team Name\Manager Name\RAW\RAW QC data.xlsx")
'Make Daily_Tracking_Dataset active
'Determine emptyRow
'Transfer Information
Set wb = Workbooks("RAW QC data.xlsx")
Set sh = wb.Sheets(1)
cAry = Array(Me.QCBX, Me.CallBX, Me.INBX, Me.AgntBX, Me.VoxBX, Me.ClntBX, Me.PolBX, Me.DateBX1, Me.AuditBX1, Me.TextBox7, Me.TextBox8, Me.OUTBX1, Me.Cbx1_1, Me.Cbx1_2, Me.Cbx1_3, Me.Cbx1_4, Me.OUTBX2, Me.Cbx2_1, Me.Cbx2_2, Me.Cbx2_3, Me.OUTBX3, Me.Cbx3_1, Me.Cbx3_2, Me.OUTBX4, Me.Cbx4_1, Me.Cbx4_2, Me.Cbx4_3, Me.OUTBX5, Me.Cbx5_1, Me.Cbx5_2, Me.Cbx5_3, Me.Cbx5_4, Me.Cbx5_5, Me.Cbx5_6, Me.Cbx5_7, Me.Cbx5_8, Me.ACBX, Me.QTBX, Me.QFBX)
With sh
For i = 1 To 39
.Cells(Rows.Count, i).End(xlUp)(2) = cAry(i - 1).Value
Next
End With
'Save the Raw data
wb.Close SaveChanges:=True
End Sub
What is happening is that it looks like it is working but when I try to submit the next one, It gives me the SAVE AS window
You have both wkb and wb in your code. Probably this is not what you intend. Just try changing wkb to wb in your code. That's a good reason to start using Option Explicit - What do Option Strict and Option Explicit do?
In general, something as simple as this should be working:
Public Sub TestMe()
'Dim wb As Workbook
Dim wkb As Workbook
Dim sh As Worksheet
Set wkb = Workbooks.Open(ThisWorkbook.Path & "\Testing.xlsx")
'Set wb = Workbooks("Testing.xlsx")
'Put your loop instead of the TEST later:
wb.Worksheets(1).Cells(1, 1) = "TEST"
Application.DisplayAlerts = False
wkb.Save
Application.DisplayAlerts = True
wkb.Close
End Sub

vba Macro to open other WB and execute Macro fails when other WB have userform show on opening

As topic implies I have a problem I cannot find any solution to.
I have a Workbook (1) with the purpose to open other WBs and run macros in them.
Everything works like a charm except when the other WB has Workbook_Open() event to open a Userform (typically it asks if the WB should be updated). Then I get error code 1004 and my code fails.
How could I supress the Workbook_Open event from triggering when I open another WB?
I have tried the setting Application.EnableEvents = False but it´s not related.
Thank you very much for any help on this topic!
Here is the code for opening the WB
Public Function wbTargetOpen(sTargetPath As String, SPassword As String) As Workbook
Dim sWBName As String
sWBName = Mid(sTargetPath, InStrRev(sTargetPath, "\") + 1, Len(sTargetPath) - InStrRev(sTargetPath, "\") + 1)
If WorkbookIsOpen(sWBName) Then
Set wbTargetOpen = Workbooks(sWBName)
If wbTargetOpen.ReadOnly = True Then
wbTargetOpen.Close
Set wbTargetOpen = Workbooks.Open(FileName:=sTargetPath, UpdateLinks:=0, ReadOnly:=False, WriteResPassword:=SPassword)
End If
Else
Set wbTargetOpen = Workbooks.Open(FileName:=sTargetPath, UpdateLinks:=0, ReadOnly:=False, WriteResPassword:=SPassword)
End If
If wbTargetOpen.ReadOnly Then sErrorCode = "ReadOnly"
End Function
All you have to do is add one word VbModeless to the other workbook which launches the userform.
Private Sub Workbook_Open()
UserForm1.Show vbModeless
End Sub
The vbModeless will launch the form but will also allow your macro to run.
Close the other userforms before you run the macros.
Sub CloseOtherUserForms()
Dim frm As UserForm
For Each frm In UserForms
If Not TypeName(frm) = "MacroForm" Then
Unload frm
End If
Next
End Sub

Using VBA to copy a spreadsheet from a secondary workbook into the primary one

I need to take a spreadsheet and compare it with a spreadsheet from another workbook. I know that I can do this using VBA, but I will need to copy a spreadsheet from another workbook so that both spreadsheets will reside within the same workbook and be accessible for comparison. How do I copy a spreadsheet from one workbook into another using VBA?
You don't need to copy the worksheets over to compare them. Simply open both WorkBooks and and set reference to there WorkSheets.
Sub CompareWorkBooks()
Dim wbPending As Workbook
Dim wsPending As Worksheet
Set wbPending = Workbooks("Items Pending")
Set wsPending = wsPending.Worksheet("Items")
Dim wbRecieved As Workbook
Dim wsRecieved As Worksheet
Set wbRecieved = Workbooks("Items Recieved")
Set wsRecieved = Worksheet("Items")
End Sub
If you provide names for Workbooks & WorkSheets and provide column information, we can give you better answers in a shorter period of time. Don't be afraid to post your code either.
If you want a user to select the target workbook and worksheet:
Create a userform
Declare targetWorkbook and tartgetWorksheet at the top of the code module
Add a command button and a combo box
When the button is clicked a file dialog is opened
A reference is now set to the open file
The names of all the worksheets are added to the combo
Changing the combo box value will set the refernce to tartgetWorksheet
Option Explicit
Public targetWorkbook As Workbook
Public tartgetWorksheet As Worksheet
Private Sub CommandButton1_Click()
Dim targetWorkbook As Workbook
Dim ws As Worksheet
Set targetWorkbook = getTargetWorkbook
If targetWorkbook = Nothing Then
MsgBox "Sowmthing went wrong", vbCritical, "Try Again"
Else
For Each ws In targetWorkbook.Worksheets
ComboBox1.AddItem ws.Name
Next
End If
End Function
Function getTargetWorkbook() As Workbook
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
On Error Resume Next
Set getTargetWorkbook = Application.Workbooks.Open(.SelectedItems(1))
On Error GoTo 0
End With
End Function
Private Sub ComboBox1_Change()
Set tartgetWorksheet = targetWorkbook.Worksheets(ComboBox1.Value)
End Sub