Close excel programmatically after user cancels file selection
Greetings all. I apologize but I incorrectly posted this question on the wrong board originally so am posting it again here. I have a VI that I wrote with some help from this site that reads in as many user selected Flat Data Files as desired into Excel. The VI opens Excel, places each Flat Data File on one row and ends, allowing the user to manipulate the Excel data as desired. I have tested it without problems with up to 100 files at a time. The VI minimizes Excel at startup so that it will not block the Select File(s) dialogue. MY problem is this: If the user cancels the file selection, it returns an error and leaves Excel open. I understand how to handle the error, but have been unable to make Excel close automatically if the action is canceled. I have tried to invoke the Close without saving node with no luck... probably because I don't understand how to apply it. Ideally, I want to take the error number to a case statement, and if it is anything other than zero (0), meaning no error, I want Excel to close down. This will eventually be an executable so I need to make this right. Can anybody help? I have attached a zip file with the VI's and some sample Flat Data Files.
Thanks
Attachments:
RTS Flat File Data.zip 103 KB
If you want anything to run after an error you must clear the error status boolean from the error cluster. To do this use the bundle by name and set the status value to FALSE, take this output cluster into the function you wish to run.
Andrew Alford
Production Test Engineering Technologist
Sustainable Energy Technologies
www.sustainableenergy.com
Similar Messages
-
How to close browser window after user log out
Hi,
Does anyone know how I can close browser window after user logs out. The scenario is when user clicks a log out button I will invalidate user session and close the browser right away in the backing bean.
Your help would be appreciated.Try run this and you'll see that it runs fine with no exceptions:
<%
String someText = "bla bla bla";
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=message.txt");
try {
ServletOutputStream os = response.getOutputStream();
os.write(someText.getBytes());
os.flush();
os.close();
} catch (Exception e) {
out.println("ERROR: " + e);
%>It looks like that after I've closed the outputStream I can't do any more processing in the JSP. Even if I remove the setContentType and setHeader methods it still behaves this way.
I'm starting to think that there's no way around this...?? -
How to close browser window after flushing a file to the browser?
I have this simple JSP, which flushes a String to the browser as a file (message.txt). The JSP gets opened in a new window when the user clicks a link.
The problem is that after the JSP has run, the browser window won't close automatically. I've tried adding a small javascript to achieve this, but i doesn't seem to even get run.
How can I close the browser window after the JSP has run?
<%
String someText = "bla bla bla";
// Flush to browser
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=message.txt");
try {
ServletOutputStream os = response.getOutputStream();
os.write(someText.getBytes());
os.flush();
os.close();
} catch (IOException e) {
return;
} catch (Exception e) {
return;
%>
<script type="text/javascript">
window.close();
</script>After the JSP has run, an empty html page with the following source can be seen:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>Try run this and you'll see that it runs fine with no exceptions:
<%
String someText = "bla bla bla";
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=message.txt");
try {
ServletOutputStream os = response.getOutputStream();
os.write(someText.getBytes());
os.flush();
os.close();
} catch (Exception e) {
out.println("ERROR: " + e);
%>It looks like that after I've closed the outputStream I can't do any more processing in the JSP. Even if I remove the setContentType and setHeader methods it still behaves this way.
I'm starting to think that there's no way around this...?? -
Memory usage of excel stays high after Macro is executed and excel crashes after trying to close it
Hi,
I'm trying to resolve an issue with an excel based tool. The macros retrieve data from an Oracle database and do calculations with the data. They also open and write into files in the same directory. The macros all run and finish the calculations. I can
continue to use and modify the sheet. I can also close the workbook, however excel memory usage I see in the windows Task manager stays elevated.If I close Excel it says: Excel stopped working and then it tries to recover information...
I assume something in the macro did not finish properly and memory was not released. I would like to check what is still open (connection, stream or any other object) when I close the workbook I would like to have a list of all still used memory. Is there
a possibility to do so.
Here the code I'm using, its reduced to functions which open something. Functions
get_v_tools() and get_change_tools() are same as get_client_positions().
Public conODBC As New ADODB.Connection
Public myPath As String
Sub get_positions()
Dim Src As range, dst As range
Dim lastRow As Integer
Dim myPath As String
lastRow = Sheets("SQL_DATA").Cells(Sheets("SQL_DATA").rows.Count, "A").End(xlUp).Row
Sheets("SQL_DATA").range("A2:AD" & lastRow + 1).ClearContents
Sheets("SQL_DATA").range("AG2:BE" & lastRow + 2).ClearContents
Sheets("SQL_DATA").range("AE3:AF" & lastRow + 2).ClearContents
k = Sheets("ToolsList").Cells(Sheets("ToolsList").rows.Count, "A").End(xlUp).Row + 1
Sheets("ToolsList").range("A2:M" & k).ClearContents
'open connection
Call open_connection
lastRow = Sheets("SQL_DATA").Cells(Sheets("SQL_DATA").rows.Count, "A").End(xlUp).Row
If lastRow < 2 Then GoTo ErrorHandling
'copy bs price check multiplications
Set Src = Sheets("SQL_DATA").range("AE2:AF2")
Set dst = Worksheets("SQL_DATA").range("AE2").Resize(lastRow - 1, Src.columns.Count)
dst.Formula = Src.Formula
On Error GoTo ErrorHandling
'new prices are calculated
newPrice_calculate (lastRow)
Calculate
myPath = ThisWorkbook.Path
'Refresh pivot table in Position Manager
Sheets("Position Manager").PivotTables("PivotTable3").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
myPath & "\[Position_Manager_v1.0.xlsm]SQL_DATA!R1C2:R" & lastRow & "C31" _
, Version:=xlPivotTableVersion14)
ErrorHandling:
Set Src = Nothing
Set dst = Nothing
If conODBC.State <> 0 Then
conODBC.Close
End If
End Sub
Sub open_connection()
Dim sql_data, sql_data_change, sql_data_v As Variant
Dim wdth, TotalColumns, startRow As Integer
Dim rst As New ADODB.Recordset
Errorcode = 0
On Error GoTo ErrorHandling
Errorcode = 1
With conODBC
.Provider = "OraOLEDB.Oracle.1"
.ConnectionString = "Password=" & pswrd & "; Persist Security Info=True;User ID= " & UserName & "; Data Source=" & DataSource
.CursorLocation = adUseClient
.Open
.CommandTimeout = 300
End With
startRow = Sheets("SQL_DATA").Cells(Sheets("SQL_DATA").rows.Count, "A").End(xlUp).Row + 1
sql_data = get_client_positions(conODBC, rst)
wdth = UBound(sql_data, 1)
Sheets("SQL_DATA").range("A" & startRow & ":AA" & wdth + startRow - 1).Value = sql_data
'Run change tools instruments
startRow = Sheets("ToolsList").Cells(Sheets("ToolsList").rows.Count, "A").End(xlUp).Row + 1
sql_data_change = get_change_tools(conODBC, rst)
wdth = UBound(sql_data_change, 1)
Sheets("ToolsList").range("A" & startRow & ":M" & wdth + startRow - 1).Value _
= sql_data_change
'open SQL for V tools instruments
startRow = Sheets("ToolsList").Cells(Sheets("ToolsList").rows.Count, "A").End(xlUp).Row + 1
sql_data_v = get_v_tools(conODBC, rst)
wdth = UBound(sql_data_v, 1)
Sheets("ToolsList").range("A" & startRow & ":L" & startRow + wdth - 1).Value = sql_data_v
conODBC.Close
ErrorHandling:
If rst.State <> 0 Then
rst.Close
End If
Set rst = Nothing
End Sub
Private Function get_client_positions(conODBC As ADODB.Connection, rst_posi As ADODB.Recordset) As Variant
Dim sql_data As Variant
Dim objCommand As ADODB.Command
Dim sql As String
Dim records, TotalColumns As Integer
On Error GoTo ErrorHandling
Set objCommand = New ADODB.Command
sql = read_sql()
With objCommand
.ActiveConnection = conODBC 'connection for the commands
.CommandType = adCmdText
.CommandText = sql 'Sql statement from the function
.Prepared = True
.CommandTimeout = 600
End With
Set rst_posi = objCommand.Execute
TotalColumns = rst_posi.Fields.Count
records = rst_posi.RecordCount
ReDim sql_data(1 To records, 1 To TotalColumns)
If TotalColumns = 0 Or records = 0 Then GoTo ErrorHandling
If TotalColumns <> 27 Then GoTo ErrorHandling
If rst_posi.EOF Then GoTo ErrorHandling
l = 1
Do While Not rst_posi.EOF
For i = 0 To TotalColumns - 1
sql_data(l, i + 1) = rst_posi.Fields(i)
Next i
l = l + 1
rst_posi.MoveNext
Loop
ErrorHandling:
rst_posi.Close
Set rst_posi = Nothing
Set objCommand = Nothing
get_client_positions = sql_data
End Function
Private Function read_sql() As String
Dim sqlFile As String, sqlQuery, Line As String
Dim query_dt As String, client As String, account As String
Dim GRP_ID, GRP_SPLIT_ID As String
Dim fso, stream As Object
Set fso = CreateObject("Scripting.FileSystemObject")
client = Worksheets("Cover").range("C9").Value
query_dt = Sheets("Cover").range("C7").Value
GRP_ID = Sheets("Cover").range("C3").Value
GRP_SPLIT_ID = Sheets("Cover").range("C5").Value
account = Sheets("Cover").range("C11").Value
sqlFile = Sheets("Cover").range("C15").Value
Open sqlFile For Input As #1
Do Until EOF(1)
Line Input #1, Line
sqlQuery = sqlQuery & vbCrLf & Line
Loop
Close
' Replace placeholders in the SQL
sqlQuery = Replace(sqlQuery, "myClent", client)
sqlQuery = Replace(sqlQuery, "01/01/9999", query_dt)
sqlQuery = Replace(sqlQuery, "54747743", GRP_ID)
If GRP_SPLIT_ID <> "" Then
sqlQuery = Replace(sqlQuery, "7754843", GRP_SPLIT_ID)
Else
sqlQuery = Replace(sqlQuery, "AND POS.GRP_SPLIT_ID = 7754843", "")
End If
If account = "ZZ" Then
sqlQuery = Replace(sqlQuery, "AND AC.ACCNT_NAME = 'ZZ'", "")
Else
sqlQuery = Replace(sqlQuery, "ZZ", account)
End If
' Create a TextStream to check SQL Query
sql = sqlQuery
myPath = ThisWorkbook.Path
Set stream = fso.CreateTextFile(myPath & "\SQL\LastQuery.txt", True)
stream.Write sql
stream.Close
Set fso = Nothing
Set stream = Nothing
read_sql = sqlQuery
End FunctionThanks Starain,
that's what I did the last days and found that the problem is in the
newPrice_calculate (lastRow)
function. This function retrieves data (sets it as arrays) which was correctly pasted into the sheet, loops through all rows and does math/calendar calculations with cell values using an Add-In("Quantlib")
Public errorMessage as String
Sub newPrice_calculate(lastRow)
Dim Type() As Variant
Dim Id() As Variant
Dim Price() As Variant
Dim daysTo() As Variant
Dim fx() As Variant
Dim interest() As Variant
Dim ObjCalend as Variant
Dim newPrice as Variant
On Error GoTo Catch
interest = Sheets("SQL_DATA").range("V2:V" & lastRow).Value
Type = Sheets("SQL_DATA").range("L2:L" & lastRow).Value Id = Sheets("SQL_DATA").range("M2:M" & lastRow).Value Price = Sheets("SQL_DATA").range("T2:T" & lastRow).Value
daysTo = Sheets("SQL_DATA").range("K2:K" & lastRow).Value
fx = Sheets("SQL_DATA").range("U2:U" & lastRow).Value
qlError = 1
For i = 2 To lastRow
If (i, 1) = "LG" Then
'set something - nothing spectacular like
interest(i, 1) = 0
daysTo(i , 1) = 0
Else
adjTime = Sqr(daysTo(i, 1) / 365)
ObjCalend(i,1) =Application.Run("qlCalendarHolidaysList", _
"CalObj", ... , .... other input parameters)
If IsError(ObjCalend(i,1)) Then GoTo Catch
'other calendar calcs
newPrice(i,1) = Application.Run( 'quantLib calcs)
End If
Catch:
Select Case qlError
Case 1
errorMessage = errorMessage & " QuantLibXL Cal Error at: " & i & " " & vbNewLine & Err.Description
ObjCalend(i,1) (i, 1) = "N/A"
End Select
Next i
Sheets("SQL_DATA").range("AB2:AB" & lastRow).Value = newPrice
'Sheets("SQL_DATA").range("AA2:AA" & lastRow).Value = daysTo
' erase and set to nothing all arrays and objects
Erase Type
Erase id
Erase Price
Set newPrice = Nothing
Is there a possibility to clean everything in:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
End Sub
Thanks in advance
Mark -
Save and close excel file using C#.
I am not sure why I get the following error for the below code. Everything seems to work otherwise.
Error found: System.Runtime.InteropServices.COMException (0x8002000B): Invalid index. (Exception from HRESULT: 0x8002000
B (DISP_E_BADINDEX))
Application _application;public void CloseFile(string filename, bool isSaveChanges)
_application.Workbooks[filename].Close(SaveChanges: isSaveChanges);I' work with excel files with connection you can save data and close connection Easy.
//connection String for xls file format.
if (fileExtension == ".xls")
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
//connection String for xlsx file format.
else if (fileExtension == ".xlsx")
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
return null;
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
dataAdapter.Fill(ds);
Best Regards
Hakim. -
Cancel download method when the user cancel the download file
I have a method that download a file ("downloadLog_action()")when the user click over the comandlink component and the dialog box is opening to save the file, but how to know that the user canceled the download file to cancel all accions.
This is the code of the commandlink in the jspx page that call the method and pass one parameter:
<af:commandLink binding="#{ConsultaValidacion.commandLink1}"
id="commandLink1"
action="#{ConsultaValidacion.descargarLog_action}"
text="Log">
<f:param name="codInstitucion"
value="#{row.CodInstitucion}"
binding="#{ConsultaValidacion.codInstitucion}"
id="codInstitucion"/>
</af:commandLink>
This is the method to download the file:
HttpServletResponse response = (HttpServletResponse)fctx.getExternalContext().getResponse();
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachement; filename=\"Log_" +
codigoInstitucion + ".txt\"");
response.setContentLength((new Long(blob.getLength())).intValue());
//Streams de entrada y salida
InputStream is;
OutputStream out;
try {
//Obtenemos el stream de entrada el cual se lo extrae de la BD
is = blob.getInputStream();
//Obtenemos el stream de salida para el cliente
out = response.getOutputStream();
//Sección de código que me permite escribir los datos en el stream de salida
int size = (new Long(blob.getLength())).intValue();
byte[] buffer = new byte[size];
int length = -1;
while ((length = is.read(buffer)) != -1) {
out.write(buffer, 0, length);
//Cerramos los streams
out.flush();
is.close();
out.close();
*//Una vez descargado todo el LOG actualizamos el contador. HERE IS THE PROBLEM BECAUSE THE COUNTER IS UPDATING WHEN THE USER CANCEL THE DOWNLOAD!!! AND ITS WRONG*
row.setNumDescargaLog(new Number(num + 1));
//Guardamos los cambios
webRvc.getAppModuleWebRvc().getDBTransaction().commit();
//Request lifecyce understands that the response is completed and no further action needs to happen
fctx.responseComplete();
} catch (IOException e) {
e.printStackTrace();
webRvc.close("Consulta bitacoras validacion");
return null;
} catch (JboException ex) {
webRvc.getAppModuleWebRvc().getDBTransaction().rollback();
webRvc.close("Consulta bitacoras validacion");
return null;
This works fine.
The problem occurs when the user cancels the download, because all the sentences run including updating the counter downloads, the counter only to be updated only when the user chooses to save the file.Hi.
The problem is when the user cancel the dowload I do not know how to capture the user's response.
How to capture the response?
if(cancelled) <------Is there a parameter to tell me this?
......<your cancel code>..... none
else
.....<your non-cancel code>...THE METHOD THAT DOWNLOAD THE FILE - "downloadLog_action()" and increment the counter
Thanks. -
I have seen this problem discussed before, but have never seen a clear cut solution.
I have a user using Excel 2013. She can create and open files locally, but when she tries to move or save to a shared network drive, she gets the error "Someone else is working in (shared drive/filename) please try again later. She's the only one using
the file most of the time.
I have done a repair on the Office installation, but the user is still having the issue, and I need to remedy this. She has appropriate file/folder permissions on the network. Really stuck on this one.Hi,
As we know, Office creates TMP files like "$.tmp file" when you open a document. Saving does not delete the files if we still have them open. And this issue occur with network drive not local disk, so
it might be caused with the account permission of the network drive. If your user has no delete permission, the temp file might be not delete after closed the file. Please try to check the permission first.
Then, if there are some mistaken operations when using the files in network drive, we could delete the temp file manually, and then the error would disappear. Please see the similar thread:
https://social.technet.microsoft.com/Forums/office/en-US/63fb4e70-4de7-45c4-a2ca-ff7209687553/excel-file-that-always-shows-a-certain-user-has-it-open?forum=excel#3e0a52bd-3ee9-4dce-8fe3-63a0937c4eed
Hope it's helpful.
Regards,
George Zhao
TechNet Community Support
It's recommended to download and install
Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
programs. -
download connections doesn't close after I cancel the download, it keep like I am downloading and only close when I disable the network adapter or reset the router or the firewall.
I use pfsense as my firewall and see the traffic not reseting to zero when I cancel download.
Also, IE doesn't have this problem. When I cancel the download the traffic drops to zero.And this problem seems to be systemwide. Since I created a new user and under which problem still exists.
Hope apple will look into it -
Read and write excel sheet data from uploded file in sharepoint site programmatically 2013
hi team,
I am working on sharepoint 2013.I want to read and write data in excel sheet (micrsoft excel) from stored file in shrepoint docoumnt library .please suggest me
vijayHi
Vijay,
check those links
http://www.sharepointwithattitude.com/archives/61
https://social.technet.microsoft.com/Forums/en-US/e760051b-a92f-473c-9ec9-0f0c36c99e40/read-and-write-excel-sheet-data-from-uploded-file-in-sharepoint-site-programmatically-2013?forum=sharepointdevelopment
Kind Regards, John Naguib Technical Consultant/Architect MCITP, MCPD, MCTS, MCT, TOGAF 9 Foundation. Please remember to mark the reply as answer if it helps. -
I have just opened my brand new Macbook Pro and I'm a first time mac user. I have tried to download flash to enable me to watch youtube clips, but on trying to download it, it says I need to close Safari but after doing so, it still won't respond. Any tips? Help?
Actually you need to quit Safari which is different from closing. With Safari open go the menu bar for Safari/Quit Safari.
Mac 101: Get Started Using A Mac -
Do I need to cancel the selection key when I close it's socket channel?
I have a non blocking server implementation and I need to know is it mandatory to call SelectionKey#cancel after I have called the SocketChannel#close to it's channel? When I close the channel, will it cancel the key automatically or what if I don't cancel the key, how does it affect to the selector?
JKThanks ejp, you are right, it's documented in SelectableChannel not in SocketChannel. My mistake.
-
Can't select user for file sharing with windows
I'm trying to share my MBPr over my LAN with my windows 8 desktop. When i go to the file sharing options, under "Windows File Sharing" section, the user account i want to share (my main account) is greyed out, so I can not select it. The other user account is selectable though.
Any reason why I can't select my main account??wow, is that all it took? I spent several hours on support chat who ultimately made me create a new user account and import all my old account data over to that one. It worked, but would have been way easier to just change the password. Oh well. It's fixed now...
-
after restoration of files via time capsule my status changed to "Guest" and I can't find the pass word for changing it back to Registered user. Any Help?
Hey mate I had this same problem exept instead of my recording disappearing my Chorus that went for 8 bars extended out to 20 bars lol and I used auto tune on it and it sounds like t-pain on a very bad day so it sounds like it does a few things when it comes up that error
-
When rebooting mac, I closed all firefox windows by clicking the cancel "x" and then clicked "close tabs". After rebooting I could not recover my open tabs, as none of the options were highlighted under History , i.e. Recently Closed Tabs or Recently Closed Windows.
We're sorry to hear that Firefox is crashing. In order to assist you better, please follow the steps below to provide us crash IDs to help us learn more about your crash.
#Enter ''about:crashes'' in the Firefox address bar and press Enter. A Submitted Crash Reports list will appear, similar to the one shown below.
#Copy the '''5''' most recent Report IDs that start with '''bp-''' and then go back to your forum question and paste that into the "Post a Reply" box. (Please don't take a screenshot of your crashes, just copy and paste the ID's. The below image is just an example of what your Firefox screen should look like)
:[[Image:aboutcrashesFx29|width=500]]
Thank you for your help!
More information and further troubleshooting steps can be found in the [[Firefox crashes - Troubleshoot, prevent and get help fixing crashes]] article. -
Hi, After installing Mavericks (Doh!) I can no longer link files in illustrator CC as the finder window closes by itself after one second or if I click on anything. It was happening with save as also, but that seems to have rectified itself by reinstalling the program. Anyone any thoughts? Im in a spot of bother!
theoutset,
There are several threads about Maverick issues just now, such as:
http://forums.adobe.com/thread/1320367?tstart=0
http://forums.adobe.com/thread/1319868?tstart=0
http://forums.adobe.com/thread/1320608?tstart=0
http://forums.adobe.com/thread/1320983?tstart=0
Astute Graphics are working on making VectorScribe compatible with Maverick, http://www.astutegraphics.com/blog/mac-os-mavericks-10-9-compatibility /
It may be worth postponing your use of Maverick until the dust has settled.
Maybe you are looking for
-
Just updated my iPhone 4 and my GF's iPhone 4 to the new OS, we share the same Apple ID and subsequently linked both phones to the same iCloud account (I will be using separate clouds from this point forward). However, after the update all of her con
-
A specific set of websites will not load.
Operating a Time Capsule behind a cable modem, I now find a very specific set of websites (those that I manage) will not load. We had a power outage yesterday which did something to my home network I think. I have rebooted modem and Time Capsule a n
-
I have been trying to download music from zippytune, but once I click on the "download" button, it takes for ever to load the next tab to download the song. I've been using this site for the past year and a half and have never had a probleme. it is o
-
Shadow clipping in Lightroom 3: how can it be avoided?
Hi all, I'm new to the forum, and I hope some of you can aid to clarify a doubt and to solve a problem. I' m starting to catalog my scanned images, and many of them are Tiff files with embedded input profiles (in Prophoto RGB color space). Many of th
-
Configuring toplink.weaving="static": Cannot apply class transformer?
All, I have managed to successfully run TopLink Essentials build 2.0_49 in JTA mode from within the web container of Sun Java System Application Server 8.1EE by providing appropriate implementations for ServerPlatform and TransactionController as des