Comma to dot replacement not working in VBA - excel

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

Related

Create unique id for each SQL record in VBA

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.

Why I could not get a full result with VBA for-loop

In the excel file as above, I want each words in the Column one (12 totally) and each words in the Column two (4 totally) to be combined into phrases generated in the Column three. I should get 12*4 = 48 phrases. Using the codes I wrote as below, only less than 30 are there with some null-value cells. Please tell me why I couldn't reach 48. Thank you.
Sub WordsCombiner()
For i = 1 To 12
For m = 1 To 4
Cells(i * m, 3).Value = Cells(i, 1).Value + Cells(m, 2).Value
Next
Next
End Sub
The following is the original words:
(Column one)
from
the
on
this
Oh
and
FYI
prices
accurate
and
items
in
Column Two
as
time
of
publication
Try this instead:
Sub WordsCombiner()
Dim i As Long
For i = 1 To 12
Dim j As Long
For j = 1 To 4
Dim k As Long
k = k + 1
Cells(k, 3).Value = Cells(i, 1).Value & " " & Cells(j, 2).Value
Next
Next
End Sub
This is dynamic so it will run for every value in Column A and Column B. It also ads the space between the groupings as you have shown in your output.
lra = last row column a
lrb = last row column b
i = counter for column c
Sub Combine()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim lra As Long, lrb As Long, a As Long, b As Long
Dim i As Long: i = 1
lra = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
lrb = ws.Range("B" & ws.Rows.Count).End(xlUp).Row
For b = 1 To lrb
For a = 1 To lra
ws.Range("C" & i) = ws.Range("A" & a) & Chr(32) & ws.Range("B" & b)
i = i + 1 '<--Next Row on Column C
Next a
i = i + 1 '<--Add Space Between Groupings
Next b
End Sub
The logic for assigning the result row is wrong. When you have i * m you get that for both "from time" and "the as" since 1*2 and 2*1 both = 2. Either use a separate counter variable or change the expression. Best way to figure this out is define three sets of values and the row they should be and find what fits.
I would prefer SQL for that task.
Select
t1.Col1, t2.col2 , t1.col1 & " " & t2.col2
FROM
(Select col1 From [Sheet1$] WHERE col1 Is Not Null) as t1,
(Select col2 From [Sheet1$] WHERE col2 Is Not Null) as t2
That query creates a carthesian product of both columns-
The result contains all combination of column1 and column2.. If the columns contain dupes and you dön't want repeating results, just use
Select Distinct t1.col1 & " " & t2.col2 As Result ...
to get rid of them.
Here's an Example, to convince the downvoter and the loopers of the simple beautiness of SQL when working with data:
Private Sub ComputeCarthesianProduct()
Dim sql As String
sql = "Select t1.[F1] & ' ' & t2.[F2] As Result FROM " _
& " (Select [F1] From [Sheet1$] WHERE [F1] Is Not Null) as t1," _
& " (Select [F2] From [Sheet1$] WHERE [F2] Is Not Null) as t2"
Debug.Print sql
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.FullName & ";Extended Properties=""Excel 12.0 Xml;Imex=1;HDR=no"";"
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
With rs
.Open sql, con
Sheet1.Range("C1").CopyFromRecordset rs 'Sheet1 is CodeName of Worksheets("Sheet1"). An explicit reference, immune to renaming the sheet
.Close
End With
.Close
End With
End Sub
If you still prefer to nest one loop for each column, you deserve to get dizzy ;)

Excel VBA SAP GUI Scripting to find row index

I am trying to change resource in SAP via excel macro. I need to find the row number of the focused cell and then insert a 'work shift' row.
I have already tried .CurrentCellRow, .SelectedRows & .GetRowPosition but unsuccessful.
Following is code I wrote till now,
Sub SAP_Entry_Plus(i As Variant)
Dim STime As String
Dim FTime As String
Dim CU As String
Session.findById("wnd[0]/tbar[1]/btn[26]").press
SlcDate = ThisWorkbook.Worksheets("Planned Shifts").Range("C" & i).Value
x = (Weekday(SlcDate, vbMonday) - 1)
MonDate = SlcDate - x
Session.findById("wnd[1]/usr/ctxtRC68K-DATUV_SEL").Text = MonDate
Session.findById("wnd[1]/tbar[0]/btn[0]").press
RNum2 = Session.findById("wnd[0]/usr/tblSAPLCRK0TC116").CurrentCellRow
RNum3 = Session.findById("wnd[0]/usr/tblSAPLCRK0TC116").SelectedRows
RNum4 = Session.findById("wnd[0]/usr/tblSAPLCRK0TC116").GetRowPosition
RNum5 = Session.findById("wnd[0]/usr/tblSAPLCRK0TC116").GetSelectedCellRow
RNum6 = Session.findById("wnd[0]/usr/tblSAPLCRK0TC116").GetCurrentCellRow
Session.findById("wnd[0]/usr/tblSAPLCRK0TC116").getAbsoluteRow(123).Selected = True
Session.findById("wnd[0]/usr/tblSAPLCRK0TC116/ctxtKAZA-KKOPF[2,6]").SetFocus
Session.findById("wnd[0]/tbar[1]/btn[6]").press
STime = Format(ThisWorkbook.Worksheets("Planned Shifts").Range("D" & i).Value, "hh:mm:ss")
FTime = Format(ThisWorkbook.Worksheets("Planned Shifts").Range("E" & i).Value, "hh:mm:ss")
CU = ThisWorkbook.Worksheets("Planned Shifts").Range("F" & i).Value
Session.findById("wnd[0]/usr/tblSAPLCRK0TC116/ctxtKAZA-BEGZT[8," & x + 1 & "]").Text = STime
Session.findById("wnd[0]/usr/tblSAPLCRK0TC116/ctxtKAZA-ENDZT[9," & x + 1 & "]").Text = FTime
Session.findById("wnd[0]/usr/tblSAPLCRK0TC116/txtKAZA-NGRAD[11," & x + 1 & "]").Text = CU
End Sub
You could try to solve with the following parameters:
set myTable = session.findById("wnd[0]/usr/tblSAPLCRK0TC116")
myRow = myTable.CurrentRow
myNumber_of_Rows = myTable.RowCount
myVis_Rows = myTable.VisibleRowCount
myPosition = myTable.VerticalScrollbar.Position
myAbsolute_Row = myPosition + myRow
The following link might also help a bit:
https://documentation.microfocus.com/help/index.jsp?topic=%2Fcom.borland.silktest.silk4net.doc%2Flangref%2FSAP%2FSapTableClass_ref.html

Numbering filtered rows

I tried to write a Macro, that does the following:
I have a table with many rows and columns, including one column that holds names
like "J63 System" or "J28 System" specifing which part of a machine every part in a row belongs to. Now I filter for one system and look at the parts: I have one empty column and want to number all the parts with the same part-number, everytime beginning from 1 whenever a new partnumber appears.
but the macro doesnt work correctly and I cant figure out why:
Option Explicit
Dim i As Integer, n As Integer, k As Integer
Dim system As String
Dim part0 As String, part1 As String
Sub temato()
n = 887
k = 888
Do
part0 = Cells(n, 2)
part1 = Cells(k, 2)
If Cells(k, 36) = "J64 Tail Rotor" Then
If part1 = part0 Then
Cells(k, 3) = Cells(k - 1, 3).Value + 1
n = n + 1
k = k + 1
Else
Cells(k, 3) = 1
n = n + 1
k = k + 1
End If
Else
k = k + 1
Debug.Print n
Debug.Print k
Do
'n bleibt
part1 = Cells(k, 2)
If Cells(k, 36) = "J64 Tail Rotor" Then
If part1 = part0 Then
Cells(k, 3) = Cells(n, 3).Value + 1
n = k
k = k + 1
Else
Cells(k, 3) = 1
n = k
k = k + 1
End If
Else
k = k + 1
End If
Loop While Cells(k, 36) <> "J64 Tail Rotor"
End If
Loop While k <= 1260
End Sub
`
Add a reference to Microsoft ActiveX Data Objects 6.1 Library then copy this macro:
Dim oConn As ADODB.Connection, rs As ADODB.Recordset, sSheet as String
Dim sWorkbookName as String
sWorkbookName = ThisWorkbook.FullName
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" &
sWorkbookName & """;Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX = 1"""
sSheet="myDataSheet1"
oConn.Open connString
'just an example of SQL, you have to customize it
sSQL = "SELECT [FIELD1], [FIELD2] FROM [" & sSheet & "$] " &
" WHERE [FIELD1] Like ""*yourmatch"" ORDER BY [FIELD1] ASC"
rs.Open sSQL, oConn, adOpenStatic, adLockOptimistic, adCmdText
'dump results on a temporary sheet or on the data sheet in an empty column
ThisWorkbook.Worksheets("tmp_sheet").Range("A2").CopyFromRecordset rs
rs.Close
oConn.Close
Set rs = Nothing
Set oConn = Nothing
Once you post the table structure and specify the desired result I shall write the SQL query

VBA and Excel Macro

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

Resources