VBA Runtime Error 1004 "Application-defined or Object-defined error" when Trying to put formula into a range - runtime-error

i'm close to throwing my laptop out the window as i'm trying to code something relatively simple, but keep getting this error.
Attempting to multiply column AA*Z.
Can anyone help???
Sub sssssss()
'
' sfd Macro
'
Range("AB8:AB6000").Formula = "=IF(AA8*Z8=0,"",AA8*Z8)"
Range("AS8:AS6000").Formula = "=IF(AA8*Z8=0,"",AA8*Z8)"
Range("AV8:AV6000").Formula = "=IF(AA8*Z8=0,"",AA8*Z8)"
Range("BQ8:BQ6000").Formula = "=IF(AA8*Z8=0,"",AA8*Z8)"
End Sub

Related

TimeSpan.Parse Not Working When Processing CSV File

I am trying to upload tracks to my SQL database via a CSV file, but when I try to process the file, I get this exception:
System.FormatException
HResult=0x80131537
Message=String was not recognized as a valid TimeSpan.
Source=<Cannot evaluate the exception source>
StackTrace:
<Cannot evaluate the exception stack trace>
Neither formatting time as hh:mm:ss or h:mm:ss works, though my CSV is very simple; a record looks like this:
TrackName,TrackLength,TrackNumber,AlbumID
Elected,00:04:05,3,6
My code is also very simple; it has worked for converting numbers and DateTimes. What am I doing wrong with the TimeSpans? I've been Googling a lot, but all I've found says TimeSpan.Parse is the best method for converting strings to timespans.
Dim csvData = From line As String In File.ReadAllLines(filenameWithPath)
Skip 1
Let CR = line.Split(",")
Select New Track With {
.TrackName = CR(0),
.TrackLength = TimeSpan.Parse(CR(1)),
.TrackNumber = CInt(CR(2)),
.AlbumID = CInt(CR(3))
}
EDIT: There is no reason for an exception to be thrown. Below is the full code for my button click event; there's only a simple If statement to check if the file upload control has a file. Nothing here should be causing problems.
Private Sub BTN_Upload_Click(sender As Object, e As EventArgs) Handles BTN_Upload.Click
If FU_CSV.HasFile Then
Dim filenameWithPath As String = Server.MapPath("~/Content/Docs/Data/" & FU_CSV.FileName)
FU_CSV.SaveAs(filenameWithPath)
Dim csvData = From line As String In File.ReadAllLines(filenameWithPath)
Skip 1
Let CR = line.Split(",")
Select New Track With {
.TrackName = CR(0),
.TrackLength = TimeSpan.Parse(CR(1)),
.TrackNumber = CInt(CR(2)),
.AlbumID = CInt(CR(3))
}
For Each t As Track In csvData
context.Tracks.Add(t)
context.SaveChanges()
Next
End If
End Sub

Asp.net: Excel file uploading does not finish but gives no error message

I'm having a rather weird problem trying to upload an Excel file and storing it in a SQL server table in an ASP.net App.
The file is not too big: about 2.5 or 3 Mb.
The problem is that the upload gets "interrupted" after loading some rows, appearently without causing any specific error, since the load process finishes by showing a success message that I'm sending to the client:
"The process finished successfuly: XXX rows were uploaded from the
file".
The problem is that the XXX rows are not all the rows from the file. Depending on how much information there is in each column of the Excel file, the process is only uploading, for instance, 15500 rows from a total of 25000 that the file has. (If there's less information in the Excel file, it can upload, lets say 20000 of the 25000 rows that it may have)... the fact is that the file is not being "completely" uploaded.
I already tried increasing the "httprequest-maxRequestLength" value in the web.config, even though the file is not bigger than the default 4Mb file upload that ASP.net has.
The code (vb.net) that I'm using upload and read the file is, basically, this:
Dim connection As DbConnection = Nothing
Dim Command As DbCommand = Nothing
Dim ConexionStringExcel As String
Dim dr As DbDataReader
Dim mensajeError as String = ""
Dim ncAdic as Integer = 0
Dim nReg as Integer = 0
'String connection for Excel 2007: for now, I'm not allowing other Excel versions
ConexionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = " & sNombreArch & ";" & _
"Extended Properties=Excel 12.0 Xml;"
'sNombreArch is the full name of the uploaded file
connection = New OleDb.OleDbConnection(ConexionStringExcel)
Command = connection.CreateCommand()
Command.CommandText = "SELECT * FROM [" + nomHojaArch + "$]"
'---
'lblMensaje is a Label object in the aspx page:
'---
lblMensaje.Visible = False
Try
'Open the Excel file
connection.Open()
'Read file content
dr = Command.ExecuteReader()
While dr.Read
Try
'Two first columns of the file are mandatory in my case...
If Not IsDBNull(dr(0)) And Not IsDBNull(dr(1)) Then
'---
'dsTempCargue is a SqlDataSource object in the aspx page
'---
dsTempCargue.InsertParameters.Item("idReg").DefaultValue = dr(0)
dsTempCargue.InsertParameters.Item("nombre").DefaultValue = dr(1)
For ncAdic = 2 To 10
If Not IsDBNull(dr(ncAdic)) Then
dsTempCargue.InsertParameters.Item(ncAdic).DefaultValue = dr(ncAdic)
Else
dsTempCargue.InsertParameters.Item(ncAdic).DefaultValue = DBNull.ToString
End if
Next
dsTempCargue.Insert()
nReg = nReg + 1
Else
mensajeError = "Column A and B of the File cannot be empty"
Exit While
End If
Catch exRead As Exception
mensajeError = "Error reading the file or saving its content: " & exRead.Message
Exit While
End Try
End While
'If there was no error, show success message
If String.IsNullOrEmpty(mensajeError) Then
mensajeError = "The process finished successfuly. " & nReg.ToString() & " rows were uploaded from the file"
End IF
Catch ex As Exception
mensajeError = "Error uploading the file: " & ex.Message
End Try
lblMensaje.Text = mensajeError
lblMensaje.Visible = True
Why do you think this uploading process is failing to read the entire file???... Any advice will be appreciated.
Thanks a lot,
Diego
For the tables that you are storing the rows in, what datatype are the various columns? Perhaps the content of one of the cells is incompatible with the column datatype. Do you have any way of checking?
Even though I'm really not sure about what could have been the cause of the error, I finally managed to get it working by changing my code to use a Third-party library that I found and that had some good comments, which is available here:
http://exceldatareader.codeplex.com/
I'm not really sure about what the original problem was and why using this library solved the issue, but It worked. (Perhaps when I have some time I'll try to find more info about this problem I had)
Thanks Patrick for your comments and all for the interest

ASP.net StackedColumn Chart Series - Overlapping & Gaps

I'm trying to deploy some charts on my web application, but am having trouble with the StackedColumn chart; the series are either overlapping each other or gapping apart from each other, the result being that the overall total is misrepresented. Here are two examples showing each problem:
http://sdrv.ms/17nzZ2k - gaps between series
http://sdrv.ms/1fg6LqW - overlapping series
This is my code to generate the chart:
Private Sub chartMonMStack_DataBinding(sender As Object, e As System.EventArgs) Handles chartMonMStack.DataBinding
Dim chart As Chart = chartMonMStack
Dim cArea As String = "area"
chart.ChartAreas(cArea).Position.Width = 85
chart.ChartAreas(cArea).Position.Height = 100
chart.ChartAreas(cArea).AxisX.MajorGrid.LineColor = Drawing.ColorTranslator.FromHtml("#999999")
chart.ChartAreas(cArea).AxisY.MajorGrid.LineColor = Drawing.ColorTranslator.FromHtml("#999999")
chart.ChartAreas(cArea).AxisX.Title = "年"
chart.ChartAreas(cArea).AxisY.Title = "NTD"
chart.ChartAreas(cArea).AxisY.LabelStyle.Format = "#,##0"
Dim conStr As String = ConfigurationManager.ConnectionStrings("GenshenPOS").ConnectionString
Dim conn As New SqlConnection(conStr)
conn.Open()
Dim sql As String = "SELECT [y], [Store], SUM([amount]) AS [NTD] FROM vwMonthly " & _
"WHERE [m] = '" & dropMonth.SelectedValue & "月' GROUP BY [y], [Store] ORDER BY [y], [Store]"
Dim sqlPoints As New SqlCommand(sql, conn)
Dim reader As SqlDataReader = sqlPoints.ExecuteReader()
While reader.Read()
If chart.Series.IndexOf(reader.Item("Store")) = -1 Then
chart.Series.Add(reader.Item("Store"))
chart.Legends.Add(reader.Item("Store"))
chart.Series(reader.Item("Store")).ChartType = SeriesChartType.StackedColumn
chart.Series(reader.Item("Store")).ChartArea = cArea
chart.Series(reader.Item("Store")).IsValueShownAsLabel = True
chart.Series(reader.Item("Store")).LabelFormat = "#,##0"
chart.Series(reader.Item("Store")).LabelForeColor = Drawing.Color.White
End If
chart.Series(reader.Item("Store")).Points.AddXY(reader.Item("y"), reader.Item("NTD"))
End While
conn.Close()
End Sub
I've read that the gaps can occur because of missing data if the series has a blank data point, however on the affected column, there are no missing data points. Additionally I don't think this can explain why in other instances, the bars overlap and do not position themselves on the chart correctly. Nevertheless I tried adding the following but to no avail.
For Each s As Series In chart.Series
chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, s)
Next
If anyone can help I'd appreciate it!
It appears that InsertEmptyPoints was the correct method for resolving the problem, however if anyone has issues with this not appearing to do anything as I did, then using additional parameters in the method could resolve your issue, as it did mine.
For Each s As Series In chart.Series
chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, 0, IntervalType.Number, MinXAxis, MaxXAxis, s)
Next
I used a 0 value in the offset section of the method (as I have no need to offset), and instead focused on the 5th (fromXValue) and 6th (toXValue) parameters to specify the range of values along my axis. The variables MinXAxis and MaxXAxis are assigned the values I need dynamically.
This resolves both the gapping and overlap for my series.
For more info on InsertEmptyPoints see msdn, however be advised it currently makes no mention of the fromXValue and toXValue parameters, I found out about them from within Visual Studio.

Classic asp - response.redirect in a sub - error handling

I wish to do the following ... Provide a page a developer can redirect to provided an error occurs ... like a vb error connection couldn't open or object couldn't be found ... or a database error is raised ... but since I moved the redirect into a sub the page doesn't actually redirect ... Is it possible that I simply can't redirect from a sub? Seems weird.
Run a stored procedure that raises an error
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "spReturnDBException"
cmd.Execute
Call a handle errors function that sets up some session parms and redirects if neccessary
HandleErrors con _
, Request.ServerVariables("PATH_INFO") _
, "An error occurred while trying to save sessions." _
, "Actual Error: " + Err.Description + " EmpNo: " + Session("EmpNo") _
+ ". QueryString: " + Request.Querystring _
, 0
This would be the sub called.
sub HandleErrors( connection, WebPagePath, GenericErrorMessage, DebugInfo, Severity)
//Check for vb errors
if Err.Number <> 0 Then
Session("WebPagePath") = WebPagePath
Session("SafeErrorMessage") = GenericErrorMessage 'Session("SafeErrorMessage") + "A connection was dropped while trying to complete sessions."
Session("DebugInfo") = DebugInfo ' Err.Description
Session("LineNo") = Err.Line
Session("StackTrace") = ""
Session("Severity") = Severity
response.redirect("Error.asp")
//error occurs
elseif connection.Errors.count <> 0 then
response.write("a database error occurred.")
// Store safe error message / # in session
Session("WebPagePath") = WebPagePath
Session("SafeErrorMessage") = GenericErrorMessage 'Session("SafeErrorMessage") + "An error has occurred while trying to save sessions."
Session("DebugInfo") = DebugInfo '"Some extra added debug info from the webpage"
Session("LineNo") = 0
Session("StackTrace") = ""
Session("Severity") = Severity
Dim objError
for each objError in connection.Errors
// Store safe error number in session
Session("SafeErrorNumbers") = Session("SafeErrorNumbers") + objError.Description
if connection.Errors.Count > 1 then
Session("SafeErrorNumbers") = Session("SafeErrorNumbers") + "|"
end if
next
response.Redirect("Error.asp")
end if
Err.Clear
end sub
To display the Error line number:
set objError = Server.GetLastError()
strErrorLine = objError.Line
Here are a couple threads on using Err.line:
http://www.daniweb.com/web-development/asp/threads/11615
http://www.sitepoint.com/forums/showthread.php?279612-ASP-Error-Handling.-Err.Line-weird-behavior
I can't explain why you are getting the results you are. I can tell you that if your code reachs a line that contains Response.Redirect that redirect will happen regardless of whether its a in a Sub procdure or not.
I would make this suggestion. Stop using using On Error Resume Next. It is very painful way to deal with exceptions.
Instead change HandleErrors into GenerateConnectionError. Its job would be to compose error source and description strings and deliberately call Err.Raise with a user define error number (I tend to use 1001).
Now your Error.asp should be installed in the root of your application as the handler for the 500.100 http status code. When a script error occurs IIS will look to the current error pages collection for the location to determine what to do. You will have set this to execute a URL and specified your Error.asp as the URL.
When Error.asp is executed it will find details about the page being requested from QueryString. Here you can also use Server.GetLastError to get an ASPError object from which you can get other details about the error.
Using this approach will detail with any script error without requiring the developer to remember to pepper their code with HandleError code. The developer need on remember to call GenerateConnectionError when performing code that is using an ADODB.Connection and even then you could probably abstract that inside an .asp include file.

Error in ASP Code

Below ASP code have some error in 'Dim MonthNum=Month("Ctxtdatefrom") '
Can help to solve this.
If session("cmbLeaveType")=2 then
set rs2 = objconn.execute("select * form Particulars where empid='" & session("empid") & "'")
if Nationality = ABC then
Dim MonthNum=Month("Ctxtdatefrom")
Dim MonthNum2=Month("ctxtdateto")
If(MonthNum=5 and monthnum2=5)
if tdays>1 then
else
set rs = objconn.execute("insert into leavebank (empid, datesubmit, datefrom, dateto....
END IF
END IF
END IF
END IF
If Nationality is "Country A" ,Number of Leave allowed to take on 5th month is 1.
If(MonthNum=5 and monthnum2=5)
if tdays>1 then
-> Can you please correct
I'm guessing that you are seeing an error like:
Microsoft VBScript compilation error '800a0401'
Expected end of statement
/test.asp, line 11
Dim MonthNum = Month("Ctxtdatefrom")
-------------^
This error is being thrown because you cannot dim and assign in one line in VBScript.
If you rewrite that to:
Dim MonthNum
MonthNum = Month("Ctxtdatefrom")
You will be closer to your aim - though you will then almost certainly hit another error - your call to the month function does not do what you think it does.
By wrapping your variable Ctxtdatefrom in double quotes you are actually passing a literal string containing the value Ctxtdatefrom to the VBScript Month function.
What you want to do is:
Dim MonthNum
MonthNum = Month(Ctxtdatefrom)
That should work so long as that variable contains a valid VBScript date format.
You can find some reading here.
The above said - based on your code, you are almost certainly going to see more errors, I'd recommend you find someone who can mentor you in ASP classic and VBScript, read some online tutorials or take things one step at a time and post detailed and specific questions here.

Resources