pretty new with VBA and there doesnt seem to be much help around the internet as I understand it is relativley old.
I am trying to use a Macro to submit data from an excel sheet into a SQL server DB.
Basically the click of a button, should pull the required data from the cells, which then put the data in the correct columns in my DB.
It is not submitting the data properley, for example one cell has the number '2' in it and it is submitting the number '0' into my database.
Can anyone advise?
Code below.
' Create the connection string.
sConnString = "provider=xxx; Data Source=xx-xxx; Initial Catalog=xxx;User ID= xx; Password=xxx;": MsgBox "Connection Succesful"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim val As String
val = Range("D5").Value
' Open the connection and execute.
conn.Open sConnString
Dim item As String
item = "INSERT INTO [Industrial].[dbo].[Header]("
item = item & " [server_name]"
item = item & " ,[date]"
item = item & " ,[amendee]"
item = item & " ,[ip_address]"
item = item & " ,[physical_location]"
item = item & " ,[host_name]"
item = item & " ,[is_it_contact]"
item = item & " ,[businesscontact]"
item = item & " ,[businessdependencies]"
item = item & " ,[backup_strategy_in_place]"
item = item & " ,[physorvirt]"
item = item & " )Values("
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
item = item & " '" & val & "'"
conn.Execute item
End Sub
You may want to check the data types and the constraints on your DB table. Its possible depending on your db type (MySQL, MSSQL, or Postgres) that if you're trying to put in a 'true' instead of true for a boolean column, it will default to 0.
Secondly, I notice is that you're placing the same value into every column.
Might I suggest an array. (intro to excel vba Arrays: http://excelvbatutor.com/vba_chp21.htm)
The below code will work assuming your data is on Sheet1 and like so...
A B (columns)
1
2 column_name_B "fifty"
3 column_name_C 10
4 column_name_D myName
(rows)
Sub testeroo()
Dim myArray(2, 2)
Dim x As Integer
Sheets("Sheet1").Activate
For x = 2 To 4
myArray(x - 2, 0) = Cells(x, 1).Value 'gets the title
myArray(x - 2, 1) = Cells(x, 2).Value 'gets the value
Next x
Then you could do a loop through the array to get your SQL statement.
End Sub
Related
Here my problem:
I import data from a SQL database to another one. To do that, I need to use an excel macro.
When I import the data into Excel => numbers are separated with comma
Then, I replace the comma by dot using the following code:
Private Function FormatNb()
With Application
.DecimalSeparator = "."
.ThousandsSeparator = " "
.UseSystemSeparators = False
End With
End Function
It works well, I can see the change in my sheet :
But, in the code, the change doesn't seem to be done 'inside' :
INSERT INTO TABLE VALUES('02/08/2022',2,24,2744808197021,2,89608192443848,75,2194137573242,0,100,024101257324,50,3323097229004,46,919059753418,54,2025413513184,54,3418502807617,54,6820297241211,31,1854991912842,53,7920608520508,35,7154998779297,58,4665489196777,64,6266403198242,9,31978130340576,63,1426811218262,49,9716606140137,0,693010807037354,13,7726097106934,600)
EDIT :
How I insert the data into the table:
'INSERT for each row into the temp table
Do Until i > lastrow
cmd.CommandText = INSERTTable(windfarm, i, lastColumn)
cmd.Execute
i = i + 1
Loop
How I create INSERTTable :
Do Until col > lastColumn
If col = 1 Or Len(sh.Cells(row, col).Value) = 23 Then
sqlstring = sqlstring & "'" & sh.Cells(row, col).Value & "',"
col = col + 1
ElseIf sh.Cells(row, col).Value = "" Then
sqlstring = sqlstring & "NULL,"
col = col + 1
Else
sqlstring = sqlstring & sh.Cells(row, col).Value & ","
col = col + 1
End If
Loop
INSERTTempTable = Left(sqlstring, Len(sqlstring) - 1) & ")"
Do you know where does the problem come ? Any solution to solve it ?
PS : I also tried to change the parameters
I have a query to get the MAX recordId from the table in SQL. I then put the value in an array and add 1 to the variable. I then use the variable to create the recordId in SQL. How do I increase the recordId by 1 for each loop?
query3 = "SELECT MAX(tbl_eInvoice_Main.RecordID) AS RecordID, " & _
"MAX(tbl_ImportDate.toolImportId) As toolImportId FROM tbl_eInvoice_Main " & _
"INNER JOIN tbl_ImportDate ON tbl_eInvoice_Main.ToolImportID = tbl_ImportDate.ToolImportID;"
rs.Open query3, con, adOpenStatic, adLockReadOnly, adCmdText
arr = rs.GetRows(1)
RecordID = arr(0, 0) + 1
ToolImportId = arr(1, 0) + 1
Worksheets("DATA").Activate
Dim rng As Range: Set rng = Application.Range("A2:IP1000")
Dim row As Range
For Each row In rng.Rows
query2 = "INSERT INTO tbl_eInvoice_Main (RecordID) values (" & RecordID & ")"
con.Execute query2
Next row
You could move your RecordID logic inside the loop like this:
For Each row In rng.Rows
arr(0, 0) = arr(0, 0) + 1
query2 = "INSERT INTO tbl_eInvoice_Main (RecordID) values (" & arr(0, 0) & ")"
con.Execute query2
Next row
However, this approach won't work well if you have multiple users. Just something to keep in mind.
I'm trying to create a message box that displays various entries for an undetermined number of columns.
I believe I want a loop, but I want the message box to display all the records available in a range and not create a new message box for each item in the range.
I want the message box to look like
Loan Summary(Price, Range, Standard Deviation):
Loan 1: (100, 5, 2)
Loan 2: (102, 4, 3)
and so on but the number of records (loans) will change each time.
I have the below code. How do I add a new line for each record in a range?
For theRep = 1 To wsv.Range("J3").Value
Average1 = Range("loanSummary").Offset(0, theRep)
Range1 = Range("loanSummary").Offset(1, theRep)
StdDev1 = Range("loanSummary").Offset(2, theRep)
MsgBox "Loan Summary (Price, Range, Standard Deviation):" & vbCrLf & vbTab & "Loan 1: " & Format(Average1, "##0.00") & ", " & Format(Range1, "##0.00") & ", " & Format(StdDev1, "##0.00")
Next
Use a string variable to hold the data then after the loop present the string in one MsgBox
Dim str As String
str = "Loan Summary (Price, Range, Standard Deviation):" & vbCrLf & vbTab
For theRep = 1 To wsv.Range("J3").Value
Average1 = Range("loanSummary").Offset(0, theRep)
Range1 = Range("loanSummary").Offset(1, theRep)
StdDev1 = Range("loanSummary").Offset(2, theRep)
str = str & "Loan " & theRep & ": (" & Format(Average1, "##0.00") & ", " & Format(Range1, "##0.00") & ", " & Format(StdDev1, "##0.00") & ")" & vbCrLf & vbTab
Next
MsgBox str
I need one macro for converting Excel spreadsheet to wiki format and post the same in wiki.
Sample data
Column-1 Column-2 Column-3
A Val1 Val1
B Val2 Val2
C Val3 Val3
Lets say that we want to post the converted table to dummy := https://wiki.com/w/Qc/MyPage
i Managed to develop the below code which almost makes a WikiSyntax.
Select the cell range to convert and run the macro.
Sub SelectionToWiki()
PadConst = "cellpadding=""1"" cellspacing=""1"" border=""1"" style=""width: 100%;"""
result = ""
result = result & " "
For i = 1 To Selection.Rows.Count
For j = 1 To Selection.Columns.Count
Dim cell As Range
Set cell = Selection.Cells(i, j)
cellStr = cell.Value
result = result & Chr(13) & "| " & cellStr
Next
result = result & Chr(13) & "|-" & Chr(13)
Next
result = "{| " & PadConst & result & "|}"
Dim MyDataObj As New DataObject
MyDataObj.SetText result
MyDataObj.PutInClipboard
MsgBox "Wiki table copied to clipboard: " & Chr(13) & Chr(13) & result
End Sub
Enhancements will be much appreciated.
I'm trying to write a VBA macro that takes the cell values in a given column, row by row, and assembles an SQL query for me to copypaste. It basically puts together text snippets and variables in a cell. The query needs cardnumbers and ordinal numbers as input, hence the variables.
The macro is almost ready, but it gets stuck in an infinite While loop.
Sub Query()
Dim Row As Integer
Row = 8
Dim Cardnumber As String
Cardnumber = Range("D" & Row)
Dim Number As Integer
Number = 1
Range("E30").Select
ActiveCell.Value = "SELECT cardnumber, first_name || ' ' || last_name FROM ( SELECT cardnumber, first_name, last_name, c.OrderNo FROM ag_cardholder ch, (SELECT '%" & Cardnumber & "%' cardmask, " & Number & " OrderNo from dual "
While IsNull(Cardnumber) = False
Row = Row + 1
Number = Number + 1
Cardnumber = Range("D" & Row)
ActiveCell.Value = ActiveCell.Value & "UNION ALL SELECT '%" & Cardnumber & "%', " & Number & " OrderNo from dual "
Wend
ActiveCell.Value = ActiveCell.Value & ") c WHERE ch.cardnumber LIKE c.cardmask ORDER BY c.OrderNo ) t"
End Sub
I've tried IsEmpty() instead of IsNull(), the result is the same. Please let me know what I'm missing here. Also, feel free to give me any advice for making the code more elegant as this is my first try at VBA. Thank you in advance for your efforts.
Being a String, Cardnumber will never be Null or Empty. It can only have zero length, Len(Cardnumber) = 0.
If Cardnumber was Variant, you could use IsEmpty to test if a cell value is blank.
There is no point to use IsNull, as a cell value in Excel is never Null. Even if a Null is fetched from a database, Excel will replace it with Empty.
Responding to your next question: I would refactor that code to:
Sub Query()
Dim InnerSelect As String
Dim CurCell As Range: Set CurCell = ActiveSheet.Range("D8")
Dim Number As Long: Number = 1
Do
Dim Cardnumber As String
Cardnumber = CurCell.Value
If Len(Cardnumber) = 0 Then Exit Do
If Len(InnerSelect) = 0 Then
InnerSelect = "SELECT '%" & Cardnumber & "%' cardmask, " & Number & " OrderNo from dual "
Else
InnerSelect = InnerSelect & "UNION ALL SELECT '%" & Cardnumber & "%', " & Number & " OrderNo from dual "
End If
Number = Number + 1
Set CurCell = CurCell.Offset(1, 0)
Loop
Range("E30").Value = _
"SELECT cardnumber, first_name || ' ' || last_name FROM ( SELECT cardnumber, first_name, last_name, c.OrderNo FROM ag_cardholder ch, (" & _
InnerSelect & _
") c WHERE ch.cardnumber LIKE c.cardmask ORDER BY c.OrderNo ) t"
End Sub