Excel VBA Suddenly Goes To Design Mode during Macro Runtime - vba

Hope someone help me with this problem.
I have a subroutine that will copy my data from this workbook to another existing workbook(Report Workbook).
When I try to run the code, during run-time once it opens the Report Workbook it suddenly stops and I've notice that it goes to design mode. Thus, hindering the execution of the routine.
But when I try to put a break point on the subroutine and continue it again. It executes without problem. This seems a bit odd.
I'm a bit out of the corner trying to figure this out.
So far this are the troubleshooting steps that I've tried.
Tried to run the Workbook in another machine.
I have tried deleting all the Workbook_Open on the Report Workbook.
Tried to delete all the Macro Codes on the Report Workbook.
Insert an error handler. Unfortunately, no error is presented.
Tried to delete the DoEvents code on the subroutine.
But still no luck. It stops the code from executing.
Private Sub TransferRawData()
Dim wsPTRawData As Worksheet, wbPTWorkBook As Workbook, wsOutputRaw As Worksheet
Dim filePath As String, FileName As String, ptTargetRow As Long
Application.EnableEvents = False
Application.StatusBar = "Exporting All Raw Data... Please wait a moment..."
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
filePath = ThisWorkbook.Path & "\"
FileName = filePath & pt_FileName
Set wbPTWorkBook = Workbooks.Open(FileName:=FileName, UpdateLinks:=0, IgnoreReadOnlyRecommended:=True)
DoEvents
Set wsPTRawData = wbPTWorkBook.Worksheets(pt_ProdRawSheet)
Set wsOutputRaw = ThisWorkbook.Sheets(merger_prodOutputSheet)
ptTargetRow = wsPTRawData.Range("A" & Rows.Count).End(xlUp).Row + 1
If lastRow(wsOutputRaw, "A") > 1 Then wsOutputRaw.Range("A2:F" & lastRow(wsOutputRaw, "A")).Copy wsPTRawData.Range("A" & ptTargetRow)
wbPTWorkBook.Close True
Set wsOutputRaw = Nothing
Set wsPTRawData = Nothing
Set wbPTWorkBook = Nothing
End Sub
BTW, I have 3 set of workbook that uses the above code. All of them will copy the data on the Report Workbook. But all of them are having trouble in executing the transfer routine.
For additional Information. Once I run the routine and it executes the Workbooks.Open Event. Here is the screenshot of the VBA Project Window and Excel Window.

Add an error handler in here and see if there are any errors that aren't being caught properly
Private Sub TransferRawData()
Dim wsPTRawData As Worksheet, wbPTWorkBook As Workbook, wsOutputRaw As Worksheet
Dim filePath As String, FileName As String, ptTargetRow As Long
Application.EnableEvents = False
Application.StatusBar = "Exporting All Raw Data... Please wait a moment..."
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
filePath = ThisWorkbook.Path & "\"
FileName = filePath & pt_FileName
On Error GoTo ErrHandler
Set wbPTWorkBook = Workbooks.Open(FileName:=FileName, UpdateLinks:=0, IgnoreReadOnlyRecommended:=True)
DoEvents
Set wsPTRawData = wbPTWorkBook.Worksheets(pt_ProdRawSheet)
Set wsOutputRaw = ThisWorkbook.Sheets(merger_prodOutputSheet)
ptTargetRow = wsPTRawData.Range("A" & Rows.Count).End(xlUp).Row + 1
If lastRow(wsOutputRaw, "A") > 1 Then wsOutputRaw.Range("A2:F" & lastRow(wsOutputRaw, "A")).Copy wsPTRawData.Range("A" & ptTargetRow)
wbPTWorkBook.Close True
Set wsOutputRaw = Nothing
Set wsPTRawData = Nothing
Set wbPTWorkBook = Nothing
ErrHandlerSave:
Debug.Print Chr(13) & "Error # " & Str(Err.Number) & " was generated on Saving" _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
End Sub
You'll see an error message come up in the Immediate window at the bottom of the VBA code. If you don't have it up or unsure how to show it LOOK HERE

Hi For Reference of others that will encounter this issue on the future.
The code itself doesn't have anything to do with the error.
After a lot of time investigating this error. I have found out that the culprit is the shortcut key that I have assigned on the Macro itself.
I have assigned a CTRL+SHIFT Key on the macro thus hindering the other macro of the other workbook that its opening.
Going forward, I made configuration on my Macro shortcut key and avoided the Shift key. As a result, the subroutine do what it needs to supposed to do.

Related

Code does not contiue after file is opened via dialogue

I'm quite confused right now... I have two modules open_files and start_comparison. From start_comparison I'm calling open_files, which is supposed to open the file open dialogue. The user is then supposed to select one file and hit open. Via start_comparison the user is supposed to open two files. However sometimes (this is where I'm confused) the code opens the first file, but then simply exit's start_comparison occasionally. Sometimes it works, sometimes not, and I have no clue when and why. Below is the code.
What I thought is: When the file dialogue is displayed, one can double click the file and the file will be openend, which would trigger a hidden exit. However, I couldn't confirm this hypthesis. When I step through, everything works fine.
What is your idea about the problem?
Sub start_comparison()
Dim cell As Range
Dim control_file_storage_bins As Range
Dim last_row_CONTROLFILE As Long
Application.ScreenUpdating = False
Set ws_control_file = ActiveWorkbook.ActiveSheet
Range("A2:Z1048576").Clear
Call open_files("PHYSICAL STOCK", 1)
Call open_files("STORAGE BINS", 2)
'Copy stock information
With ws_control_file
.Range("A2:A" & last_row_PHYSICALSTOCK).Value = ws_physical_stock.Range("B2:B" & last_row_PHYSICALSTOCK).Value
.Range("B2:B" & last_row_PHYSICALSTOCK).Value = ws_physical_stock.Range("C2:C" & last_row_PHYSICALSTOCK).Value
.Range("C2:C" & last_row_PHYSICALSTOCK).Value = ws_physical_stock.Range("J2:J" & last_row_PHYSICALSTOCK).Value
.Range("D2:D" & last_row_PHYSICALSTOCK).Value = ws_physical_stock.Range("K2:K" & last_row_PHYSICALSTOCK).Value
.Range("E2:E" & last_row_PHYSICALSTOCK).Value = ws_physical_stock.Range("E2:E" & last_row_PHYSICALSTOCK).Value
End With
Set control_file_storage_bins = ws_control_file.Range("A2:A" & last_row_PHYSICALSTOCK)
For Each cell In rng_STORAGEBIN
If (WorksheetFunction.CountIf(control_file_storage_bins, cell.Value) = 0) Then 'Storage Bin empty
With ws_control_file
last_row_CONTROLFILE = .Cells(Rows.Count, "A").End(xlUp).Row + 1
.Cells(last_row_CONTROLFILE, "A").Value = cell.Value
.Range("B" & last_row_CONTROLFILE & ":E" & last_row_CONTROLFILE).Value = "BIN EMPTY"
End With
End If
Next cell
wb_physical_stock.Close (False)
wb_storage_bins.Close (False)
Application.ScreenUpdating = True
MsgBox "Success!"
End Sub
Other procedure:
Sub open_files(file_type As String, wb_object As Integer)
Dim last_row_STORAGEBIN As Long
MsgBox "Please select the relevant " & file_type & " extract!"
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
Workbooks.Open (.SelectedItems(1))
Select Case wb_object
Case 1 'Physical Stock
Set wb_physical_stock = ActiveWorkbook
With wb_physical_stock
Set ws_physical_stock = ActiveSheet
last_row_PHYSICALSTOCK = ws_physical_stock.Cells(Rows.Count, "A").End(xlUp).Row
End With
Case 2 'Storage Bins
Set wb_storage_bins = ActiveWorkbook
With wb_storage_bins
Set ws_storage_bins = ActiveSheet
last_row_STORAGEBIN = ws_storage_bins.Cells(Rows.Count, "A").End(xlUp).Row - 1
Set rng_STORAGEBIN = ws_storage_bins.Range("A2:A" & last_row_STORAGEBIN)
End With
End Select
End With
End Sub
In case, here is the private variable declaration:
Private wb_physical_stock As Workbook, wb_storage_bins As Workbook
Private ws_physical_stock As Worksheet, ws_storage_bins As Worksheet, ws_control_file As Worksheet
Private last_row_PHYSICALSTOCK As Long
Private rng_STORAGEBIN As Range
EDIT: I was now checking the procedure open_files with breakpoints. If I set a breakpoint BEFORE Workbooks.Open and run from there again with F5 everything is fine. However, if I set a breakpoint AFTER Workbooks.Open, the breakpoint isn't even triggered. Any ideas?
EDIT2: Previously the macro was started via a short-cut. Now I changed that to an ActiveX-Control and it works fine. Same tested with simple forms and buttons (form control).
If you suspect that opening a file triggers some code, disable events before opening it - this will prevent to execute any (autoexec-) macros withing that file.
Another topic that you should address is that the user might press the "Cancel"-button, else you will run into a runtime error. You can check this with the result of the show-method, it will return False if the dialog was cancelled
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
if .Show then
application.EnableEvents = False
Workbooks.Open (.SelectedItems(1))
application.EnableEvents = True
(...)
else
' You have to make up your mind what to do in that case...
end if
end with

VBA Issues with Inserting Multiple PDF Objects Within a Loop

My set-up is that I have a bunch of blank templates in a folder. Inside each blank template is a fund code (it is the only thing in the template)
The below macro I created (in an external workbook) goes through the folder with the templates, opens each template, and "fills it out" via a loop.
Basically my macro opens each template, assigns the fund code to a variable and then uses that variable in combination with some text strings to pull in other worksheets/PDF objects related to that specific fund code.
My issue is that in a more meaty version of the below code, I added maybe four or five more PDF objects to insert. It'll go through some of the templates and then randomly stop on a random fund code at a random pdf object insert line saying either "object cannot be found" or "object cannot be inserted"
If I press debug and then press F8 to run that line again, it is able to insert the object no problem. So perhaps my code is running too fast for adobe to handle? I am unsure. Perhaps my code isn't doing things as efficiently as possible. This would save sooo much time for my team, I just can't be having it work half the time.
(also the file names have definitely been correct, so that is not an issue)
Public Sub test()
Set currentbook = ActiveWorkbook
Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim wbk As Workbook
Dim filename1 As String
Dim Path As String
Dim a As Long
Path = "C:\Users\Bob\Desktop\Workbooks\"
filename1 = Dir(Path & "*.xlsm")
'--------------------------------------------
'OPEN EXCEL FILES
Do While Len(filename1) > 0 'IF NEXT FILE EXISTS THEN
Set wbk = Workbooks.Open(Path & filename1)
wbk.Activate
'Gets Fund Code
Sheets("Initialize").Select
Dim FdCode As String
FdCode = Worksheets("Initialize").Range("D8")
'--------------------------- PDF ADDS
'Add PDF TB----------------------------------------------------
Worksheets("F.a - Working TB").OLEObjects.Add filename:="C:\Users\Bob\Desktop\Raw Reports\R122 04.30.16 - 04.30.17\" & FdCode & " 04.30.16 TB.PDF", Link:=False, DisplayAsIcon:=False, Left:=40, Top:=40, Width:=150, Height:=10
On Error GoTo 0
'Add PDF Closed Options----------------------------------------------------'
Worksheets("T300.1 - Options (Closed)").OLEObjects.Add filename:="C:\Users\Bob\Raw Reports\Other Reports 04.30.16-04.30.17\Breakout\" & FdCode & " other 04.30.17_ CLOSED OPTIONS POSITION REPORT.PDF", Link:=False, DisplayAsIcon:=False, Left:=40, Top:=40, Width:=150, Height:=10
On Error GoTo 0
ActiveWorkbook.Save
wbk.Close False
filename1 = Dir
Loop
Application.ScreenUpdating = True
End Sub

Wait for big files to open in Excel

I've been trying to loop over a bunch of big .csv files in VBA. Each of them is approximately 50MB. At every iteration I open a new CSV to manipulate data but when the .csv is opening there is a downloading message saying that the file is opening and the progress bar always gets stuck at some point while the VBA is waiting for it to finish.
Actually the .csv is opened because if I click "cancel" on the progress bar the code continues running well but I have to do a manual action at every iteration.
My guess is that VBA goes to the next step while the file is not opened or something like that so maybe if I do a Sleep or something like that it could work but what I tried did not work for now. (I already tried Application.EnableEvents = False). Here is my code:
Sub GetOptions()
Application.DisplayAlerts = False
Application.EnableEvents = False
Set Dates = Sheets("Dates")
Set Res = Sheets("Options")
Dim dateToday As Date
ETF = "SPY"
nrows = Dates.Cells(Rows.Count, 1).End(xlUp).Row
For i = 708 To nrows
If Dates.Cells(i, 2).Value = "B" Then
dateToday = Dates.Cells(i, 1).Value
dateYear = Year(dateToday)
stringOpening = "P:\Options Database\CSV\" & dateYear & "\bb_" & dateYear & "_" & GetMonth(dateToday) & "\bb_options_" & Format(dateToday, "yyyymmdd") & ".csv"
Workbooks.Open stringOpening, UpdateLinks:=0, ReadOnly:=True
Set Options = Workbooks("bb_options_" & Format(dateToday, "yyyymmdd")).Sheets(1)
Do things...
Workbooks("bb_options_" & Format(dateToday, "yyyymmdd")).Close SaveChanges:=False
End If
Next i
End Sub
A trick would be :
to open them as Read/Write files,
wait for the Write status which indicates that it is fully opened
set back the file to Read Only
This code loops until the file goes into a Write status :
Sub myWaitForFileOpen()
Dim wb As Workbook
Set wb = Application.Workbooks.Open("C:\File.xls")
Do Until wb.ReadOnly = False
wb.Close
Application.Wait Now + TimeValue("00:00:01")
Set wb = Application.Workbooks.Open("C:\File.xls")
Loop
'Then the code that needs that Workbook open here!
'Or Call That other macro here!
End Sub
Here is your full code, that will open the CSV in Read/Write until it is fully loaded and then put it back to read only :
Sub GetOptions()
Dim wB As Workbook
Application.DisplayAlerts = False
Application.EnableEvents = False
Set Dates = Sheets("Dates")
Set Res = Sheets("Options")
Dim dateToday As Date
ETF = "SPY"
nrows = Dates.Cells(Rows.Count, 1).End(xlUp).Row
For i = 708 To nrows
If Dates.Cells(i, 2).Value = "B" Then
dateToday = Dates.Cells(i, 1).Value
dateYear = Year(dateToday)
stringOpening = "P:\Options Database\CSV\" & dateYear & "\bb_" & dateYear & "_" & GetMonth(dateToday) & "\bb_options_" & Format(dateToday, "yyyymmdd") & ".csv"
Set wB = Workbooks.Open(stringOpening, UpdateLinks:=0, ReadOnly:=False)
Do Until wB.ReadOnly = False
wB.Close
Application.Wait Now + TimeValue("00:00:01")
Set wB = Application.Workbooks.Open("C:\My Files\AAA.xls")
Loop
wB.ReadOnly = True
Set Options = wB.Sheets(1)
Do
'things...
Loop
wB.Close SaveChanges:=False
End If
Next i
End Sub
If you want to open the file and use it immediately Excel might
give an error because Excel activates file opening process and goes to execute next statement. A quick and dirty workaround for not very long files is to introduce an extra code that is not related to a file thus keeping Excel busy while file is going through the opening process.

Error when use Application.run to run a macro from another workbook

I need to run multiple scenarios in a excel model. In the current model, each scenario has to be load manually, and each run takes over 3 hours. I also need to save the model result in a new workbook.
I'm writing a macro to allow scenarios automatically load in the model, run, and save as a new workbook. My code is below. The problem is when it goes to the code line "Application.run ... ", Run time error 1004: Application defined or object defined error.
Please help!
Private Sub CommandButton1_Click()
Dim ScentoRun, Path, N As String
Dim DestCom, Target As Range
Dim SCount, x As Integer
Path = "F:\"
SCount = Workbooks("Scenarios to Run").Worksheets("Sheet1").Cells(6, Columns.Count).End(xlToLeft).Column
For x = 1 To SCount
Workbooks.Open Filename:=Path & "The Model.xlsm"
Workbooks("Scenarios to Run").Worksheets("Sheet1").Columns(x).Copy
Workbooks("The Model").Worksheets("Scenarios").Columns(6).PasteSpecial
ScentoRun = Workbooks("The Model").Worksheets("Scenarios").Range("F6").Value
Application.DisplayAlerts = False
Workbooks("The Model").SaveAs Filename:=Path & ScentoRun, FileFormat:=52
Application.DisplayAlerts = True
Workbooks(ScentoRun).Worksheets("Results").Range("F8") = Workbooks(ScentoRun).Worksheets("Scenarios").Range("F6")
Workbooks(ScentoRun).Activate
N = Workbooks(ScentoRun).name
Application.Run "'N'!loadScenario" '----- ERROR HERE
Workbooks(ScentoRun).Save
Workbooks(ScentoRun).Close (True)
Next x
End Sub
Application.Run "'" & N & "'!loadScenario" '----- ERROR HERE

excel macro save sheets as csv with specific delimiter and enclosure

I am a total dummy as for vb and excel, have tried to combine 2 macros that I have found around here, into 1, but obviously did something terribly wrong and now i'm stuck.. First I just used this macro (saved it in as personal.xlsb so as to be able to use it in any workbook)
Sub CSVFile()
Dim SrcRg As Range
Dim CurrRow As Range
Dim CurrCell As Range
Dim CurrTextStr As String
Dim ListSep As String
Dim FName As Variant
FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
ListSep = ";"
If Selection.Cells.Count > 1 Then
Set SrcRg = Selection
Else
Set SrcRg = ActiveSheet.UsedRange
End If
Open FName For Output As #1
For Each CurrRow In SrcRg.Rows
CurrTextStr = ìî
For Each CurrCell In CurrRow.Cells
CurrTextStr = CurrTextStr & """" & GetUTF8String(CurrCell.Value) & """" & ListSep
Next
While Right(CurrTextStr, 1) = ListSep
CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
Wend
Print #1, CurrTextStr
Next
Close #1
End Sub
That plus the GetUTF8String function code. Now that was working fine. Then I have thought well why not just experiment with my limited (that is a serious understatement) vb understanding, added the following code and changed the CSVFile sub into a function, which I then called from the sub below, with the output file name as a parameter (to be used instead FName = Application.GetSaveAsFilename). I thought yeah, this code saves all sheets automatically, now let's just make sure that the encoding and delimiter/enclosure setting function runs before each sheet is saved. It doesn't seem right but I thought hey why not try..
Public Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven
' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
' Save the file in current director
OutputPath = ThisWorkbook.Path
If OutputPath <> "" Then
Application.Calculation = xlCalculationManual
' save for each sheet
For Each Sheet In Sheets
OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv"
' make a copy to create a new book with this sheet
' otherwise you will always only get the first sheet
Sheet.Copy
' this copy will now become active
CSVFile(OutputFile)
ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Next
Application.Calculation = xlCalculationAutomatic
End If
Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Exit Sub
Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
"Source: " & Err.Source & " " & vbCrLf & _
"Number: " & Err.Number & " " & vbCrLf & _
"Description: " & Err.Description & " " & vbCrLf
GoTo Finally
End Sub
Saved that and with that I have managed to achieve something very different. On opening any workbooks, that macro runs and opens up my sheets from that particular workbook as csv files (without saving them). Now I am like Alice in Wonderland. How come it is running on file open? That is not desirable, so I went back to the macro code and changed it back to just the csvfile sub. Well that didn't help, no idea what I did there, was definitely editing the same macro... So I deleted the macro, the modul, I cannot imagine where the thing now is but it's still running + I get this warning that macros were deactivated. Can't get rid of it! Now lads, I'm sorry for the total lack of professionality from my side, this was just supposed to be a small favor for a client, without wasting loads of time learning vb, coz my boss doesn't like that... I am of course interested in how to achieve the goal of saving the sheets automatically after setting the deimiter and enclosure in them. And at this moment I am very interested in how to get rid of that macro and where it is hiding.. What have I done?! Thank you for your patience!
I think the problem lies with the line
OutputPath = ThisWorkbook.Path
Because you are running this from your personal.xlsb which is stored in your XLSTART folder it has created the CSV files in the same location. When Excel starts it will try and load any files that it finds in that location.
Just locate your XLSTART folder and delete any CSV files you find there.
Try using
OutputPath = ActiveWorkbook.Path
XLSTART folder location, dependent on your system, is probably something like:
C:\Users\YOURNAME\AppData\Roaming\Microsoft\Excel\XLSTART