select multiple column from excel in VBA - sql
How can I select multiple column in Excel file using Vba. because I have excel file contains 580 columns.
I try using Query below, but its only can select 255 columns.
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & TxtPath.Text & "; Extended Properties=""Excel 12.0 Xml; HDR=Yes""")
ExcelConnection.Open()
Dim expr As String = "select * FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "data source=" & DBServer1 & "; initial catalog=" & DBDataBase1 & "; persist security info=true; user id=" & DBUSer1 & "; password=" & DBPass1
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "TMP_UPLOAD_ISP"
Try
objDR = objCmdSelect.ExecuteReader
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
I try by using select column header (220 Columns to select) ,its getting error until I reduce down to 100 columns.
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & TxtPath.Text & "; Extended Properties=""Excel 12.0 Xml; HDR=Yes""")
ExcelConnection.Open()
Dim expr As String = "select Plan_Year,Colom4,Colom6,Colom7,Colom21,Colom22,Colom24,Colom25,Colom27,Colom28,Colom33,Colom34,Colom38,Colom39,Colom41,Colom42,Colom47,Colom48,Colom49,Colom50,Colom51,Colom52,Colom66,Colom67,Colom69,Colom70,Colom72,Colom73,Colom78,Colom79,Colom83,Colom84,Colom86,Colom87,Colom92,Colom93,Colom94,Colom95,Colom96,Colom97,Colom111,Colom112,Colom114,Colom115,Colom117,Colom118,Colom123,Colom124,Colom128,Colom129,Colom131,Colom132,Colom137,Colom138,Colom139,Colom140,Colom141,Colom142,Colom156,Colom157,Colom159,Colom160,Colom162,Colom163,Colom168,Colom169,Colom173,Colom174,Colom176,Colom177,Colom182,Colom183,Colom184,Colom185,Colom186,Colom187,Colom201,Colom202,Colom204,Colom205,Colom207,Colom208,Colom213,Colom214,Colom218,Colom219,Colom221,Colom222,Colom227,Colom228,Colom229,Colom230,Colom231,Colom232,Colom246,Colom247,Colom249,Colom250,Colom252,Colom253,Colom258,Colom259,Colom263,Colom264,Colom266,Colom267,Colom272,Colom273,Colom274,Colom275,Colom276,Colom277,Colom303,Colom304,Colom306,Colom307,Colom309,Colom310,Colom315,Colom316,Colom320,Colom321,Colom323,Colom324,Colom329,Colom330,Colom331,Colom332,Colom333,Colom334,Colom348,Colom349,Colom351,Colom352,Colom354,Colom355,Colom360,Colom361,Colom365,Colom366,Colom368,Colom369,Colom374,Colom375,Colom376,Colom377,Colom378,Colom379,Colom393,Colom394,Colom396,Colom397,Colom399,Colom400,Colom406,Colom407,Colom410,Colom411,Colom413,Colom414,Colom419,Colom420,Colom421,Colom422,Colom423,Colom424,Colom438,Colom439,Colom441,Colom442,Colom444,Colom445,Colom450,Colom451,Colom455,Colom456,Colom458,Colom459,Colom464,Colom465,Colom466,Colom467,Colom468,Colom469,Colom483,Colom484,Colom486,Colom487,Colom489,Colom490,Colom495,Colom496,Colom500,Colom501,Colom503,Colom504,Colom509,Colom510,Colom511,Colom512,Colom513,Colom514,Colom528,Colom529,Colom531,Colom532,Colom534,Colom535,Colom540,Colom541,Colom545,Colom546,Colom548,Colom549,Colom554,Colom555,Colom556,Colom557,Colom558,Colom559 FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "data source=" & DBServer1 & "; initial catalog=" & DBDataBase1 & "; persist security info=true; user id=" & DBUSer1 & "; password=" & DBPass1
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "TMP_UPLOAD_ISP"
Try
objDR = objCmdSelect.ExecuteReader
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
How can I Select column that I want to select (220 columns intermittently).
You are using the ACE provider and that means you are bound by the limitations of MS Access. Access has a maximum field limit of 255 (see: Access 2016 specifications).
Depending on the source worksheet, you could use a range query to retrieve multiple result sets and then merge them.
Select * From [SheetName$A1:IU]
then
Select * From [SheetName$UI1:SQ]
Column "UI" is column number 255 and column "SQ" is column number 511.
If you are not familiar with this range syntax, omitting the row on the end column tells it to seek from the starting row until no data is found in the column range.
Related
sqlite update in a loop take to long
I am updating only 20 rows in a loop but the best performance I get is around 2.5 seconds for the 20 rows. What can I do to make this simple update faster? This is what Iv'e tried: Dim connectionString As New SQLite.SQLiteConnection("data source=" & Application.StartupPath & "\db.db3; Version=3;") Dim connection = New SQLite.SQLiteConnection(connectionString) connection.Open() Dim com3 As New System.Data.SQLite.SQLiteCommand(connection) For Each row As DataRow In table.Rows com3.CommandText = "UPDATE Results SET LastScore=" & row.Item("position") & " WHERE TeamID='" & row.Item("teamid") & "'" com3.ExecuteNonQuery() Next connection.Close() AND Dim connectionString As New SQLite.SQLiteConnection("data source=" & Application.StartupPath & "\db.db3; Version=3;") Using con As New SQLiteConnection(connectionString) con.Open() Using c As New SQLiteCommand(con) c.CommandText = "UPDATE Results SET LastScore= #Pos WHERE TeamID = #ID" For Each row As DataRow In table.Rows c.Parameters.AddWithValue("#Pos", row.Item("position")) c.Parameters.AddWithValue("#ID", row.Item("teamid")) c.ExecuteNonQuery() Next End Using con.Close() End Using
Thanks to muffi's answer this is now resolved. Add BeginTransaction() Dim connectionString As New SQLite.SQLiteConnection("data source=" & Application.StartupPath & "\db.db3; Version=3;") Using con As New SQLiteConnection(connectionString) con.Open() Using t As SQLiteTransaction = con.BeginTransaction() Using c As New SQLiteCommand(con) c.CommandText = "UPDATE Results SET LastScore= #Pos WHERE TeamID = #ID" For Each row As DataRow In table.Rows c.Parameters.AddWithValue("#Pos", row.Item("position")) c.Parameters.AddWithValue("#ID", row.Item("teamid")) c.ExecuteNonQuery() Next End Using t.Commit() End Using con.Close() End Using
Create table from Excel file
I'm trying to create a temp table on my database from an Excel file uploaded by the user. I cannot understand where is the problem and why Visual Studio is throwing that exception. Code Private Sub Excel_Load(ByVal filePath As String) Dim myConn As SqlConnection Dim myCmd As SqlCommand Dim sqlCmd As String Dim filename As String = Path.GetFileNameWithoutExtension(filePath) 'Setting up Connection' myConn = New SqlConnection("Server=*****;Database=*****;User ID=*****;Password=*****;Integrated Security=SSPI;") myConn.Open() 'Create table' sqlCmd = "CREATE TABLE XlsTemp AS (SELECT * FROM EXCELLINK [" & filename & "$])" 'Execute Query' myCmd = myConn.CreateCommand() myCmd.CommandText = sqlCmd myCmd.ExecuteNonQuery() myConn.Close() End Sub Exception SqlException: The object name 'EXCELLINK' is not valid. Peu_UNRAE is my Excel file.
At the end I come up with this solution: Dim MyConnection As System.Data.OleDb.OleDbConnection Dim fileExcelType As String //Get the file extension in order to use the propper provider If IO.Path.GetExtension(fileExcel.ToUpper) = ".XLS" Then fileExcelType = "Excel 8.0" MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";") Else fileExcelType = "Excel 12.0" MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";") End If //Opening excel connection MyConnection.Open() Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME") Dim MyCommand As OleDbDataAdapter = New OleDbDataAdapter(String.Format("SELECT * FROM [{0}] ", myTableName), MyConnection) MyCommand.TableMappings.Add("Table", " ") MyCommand.Fill(dt) //Closing connection MyConnection.Close() Remarks: I used // for the comments because the standar ' was giving some problem here on StackOverflow
Search between two dates in access database using sql
This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February. Private Sub Search_Record() Dim conn As New OleDbConnection Dim cmd As New OleDbCommand Dim da As New OleDbDataAdapter Dim dt As New DataTable Dim sSQL As String = String.Empty Dim bookdetials As New frmContactDetails Try 'get connection string declared in the Module1.vb and assing it to conn variable conn = New OleDbConnection(Get_Constring) conn.Open() cmd.Connection = conn cmd.CommandType = CommandType.Text sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook" If CheckBox1.Checked = True Then sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _ " AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'" End If cmd.CommandText = sSQL da.SelectCommand = cmd da.Fill(dt) Me.dtgResult.DataSource = dt Label4.Text = dt.Rows.Count Catch ex As Exception MsgBox(ErrorToString) Finally conn.Close() End Try End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked use text instead of datetime in the db make sure the datetimepicker enters "short format" data
Getting "data type mismatch in criteria expression" when I am trying to save date in excel vb form
I have a user form from which I want to save data into excel, I can save a normal string and integer but when I am trying to save data from Label13(contains date selected from calendar) in below code, it gives me error as "data type mismatch in criteria expression" Try Dim MyConnection As System.Data.OleDb.OleDbConnection Dim dataSet As System.Data.DataSet Dim MyCommand As System.Data.OleDb.OleDbDataAdapter Dim path As String = "D:\Hotel\RoomAvailability.xls" Dim Sqlq As String Dim Booked_From As string = Label13.Text Dim Room_Number As String = 202 MsgBox(Booked_From) MsgBox(Room_Number) Sqlq = "Update [Sheet1$] Set [Booked_From] = " Sqlq = Sqlq & "'" & Booked_From & "'" Sqlq = Sqlq & " where [Room_Number] =" Sqlq = Sqlq & "'" & Room_Number & "'" MsgBox(Sqlq) MyConnection = New System.Data.OleDb.OleDbConnection( "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;") MyCommand = New System.Data.OleDb.OleDbDataAdapter(Sqlq, MyConnection) dataSet = New System.Data.DataSet MyCommand.Fill(dataSet) DataGridView1.DataSource = dataSet.Tables(0) MyConnection.Close() Catch ex As Exception MsgBox(ex.Message.ToString) End Try Also what should be the format of cell in Excel in which i want to store date from Label13 ?
Type Mismatch when combining two csv files in VB
I had my code working just fine, but when I generated new updated versions of the CSV files it suddenly errors out on me and gives me a type mismatch catch. Here is the code that I have right now. Dim A As String = "ADusers.csv" Dim B As String = "MlnExp.csv" Dim filePath As String = "C:\CSV" Try Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & (filePath) & "\;Extended Properties='text;HDR=Yes'" Dim sSql As String = "SELECT *" _ & "FROM ([" & (B) & "] B LEFT JOIN [" & (A) & "] A ON B.EmployeeNumber = A.employeeID)" Dim conn As OleDb.OleDbConnection = New OleDb.OleDbConnection(ConnectionString) Dim Command As OleDb.OleDbCommand = New OleDb.OleDbCommand(sSql, conn) Command.CommandType = CommandType.Text conn.Open() Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sSql, conn) Dim dt As DataTable = New DataTable da.Fill(dt) DataGrid1.DataSource = dt DataGrid1.Update() conn.Close() lblStatus.Text = "CSV combined... Now saving to file." Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.Exclamation) End Try Before it would go through, combine the two CSV files, and then display them in my datagrid. But now my catch is throwing back Type mismatch in expression
i would check B.EmployeeNumber = A.employeeID in both of your file one is a text value (left align) and the other is a a interger(right align)