Excel macro to prepare query string based on rows - excel

I have one excel Sheet having below records
id Empname state
1 steve NJ
2 karl NYC
I have to write one macro to prepare sql update stement like below and insert into new sheet within the same workbook.
UPDATE emp SET state='NJ' WHERE id=1
UPDATE emp SET state='NYC' WHERE id=2
Any suggestions or ideas please.
Regards,
Raju

Use below sub and you should be all set
Sub generateUpdate()
Dim myRow As Integer: myRow = 2 'Starting Row of data in source table
Dim temp As Integer: temp = 1
Do Until Sheet1.Cells(myRow, 1) = "" 'Loop until you find a blank
'Do Until myRow = 5 '5 is Row number till while you wish to loop
Sheet2.Cells(temp, 1) = "UPDATE emp SET state='" & Sheet1.Cells(myRow, 3) & "' where id = " & Sheet1.Cells(myRow, 1)
myRow = myRow + 1
temp = temp + 1
Loop
End Sub

You could do this with formulas; there's no need to write a macro (if I read your requirements correctly).
If your data is in Sheet1!A2:C3, then on Sheet2 you could start in cell A1 with the formula:
="UPDATE emp SET state = '" & Sheet1!C2 & "' WHERE id = " & Sheet1!A2
And then extend the formula down the column to repeat the pattern. After that you can simply copy the cells and paste the query into wherever you're going to use it.

Related

How To Consolidate Multiple Rows Into One Row

My situation is as follows. I have a list of around 2k student accounts and sort the information to a specific format that i can format to our new CRM. The way the data is presented initially makes that problematic.
As you can see on the first screenshot, every student's university choice is presented in a separate row. So if a student has chosen more than one university, data about it is stored in 2-6 rows (each student can select 1 to 6 universities) repeating his personalID, name, forename and DoB every line.
What I need to achieve is to remove repeating information and store all data about each student in one row per student(example on screenshot 2).
I have no idea how to achieve this using VBA. I was trying with IFs, loops and arrays but without any progress. I need help on how to accomplish that using VBA.
Please let me know if you need more information. I will try to explain it in more details if required.
Screenshot 1
Screenshot 2
EDIT: This is the part of the report. I am working on a macro that will format it to our needs and will give us more info about the student's accounts. That is why I am asking for help in VBA.
No need to use VBA for this. Power Query will help you better. Have a look here: https://excelgorilla.com/power-bi/power-query/aggregate-text-values-using-group-by/
This seems to work. I'm new to VBA and programming in general so it's possibly not the most efficient solution and can definitely be improved.
Instead of working with a blank sheet, it transforms the current data to the format you wanted. You can add field headings where you want.
Edit: It assumes that each Student has 5 universities in the list. The code can be adjusted to account for any number by just adjusting the target range dynamically.
Edit 2: I added the change to account for students who've entered any number of universities between 1 to 5. Let me know if this gets it done!
Sub ReArrange_Data()
Dim lrow As Long
lrow = Cells(Rows.Count, 1).End(xlUp).Row
Dim First As Integer
Dim Last As Integer
Dim test As Integer
Dim test1 As Integer
Dim student_range As Range
Dim student_rows As Integer
Dim target_range As Range
First = 2
For i = 2 To lrow
Last = First
If Cells(First, "D").Value = "" Then GoTo Break 'reached end of data
While Cells(Last, "D").Value = Cells(Last + 1, "D").Value
Last = Last + 1
Wend
If Last <> First Then 'check if mulitiple uni and build range
Set student_range = Range("E" & First & ":" & "E" & Last)
student_rows = student_range.Rows.Count
If student_rows = 5 Then
Set target_range = Range("E" & First & ":" & "I" & First)
ElseIf student_rows = 4 Then
Set target_range = Range("E" & First & ":" & "H" & First)
ElseIf student_rows = 3 Then
Set target_range = Range("E" & First & ":" & "G" & First)
ElseIf student_rows = 2 Then
Set target_range = Range("E" & First & ":" & "F" & First)
End If
Else
GoTo Skip 'student entered one uni, go to next loop
End If
target_range = Application.WorksheetFunction.Transpose(student_range.Value) 'row to column
Rows(First + 1 & ":" & Last).EntireRow.Delete
Skip: 'delete repeated entries
First = First + 1
Next i
Break:
End Sub

How to count and copy entries with Excel VBA

currently I am working with an Excel report that has 135.000 rows. There are assets listed in it and I want to count each asset and write it into another worksheet.
I have tried to write a VBA script, which you can find below. It just copies one entry but does not iterate over each row of the worksheet.
Sub assetVulnerabilityCount()
With Sheets("tblExport")
assetCount = 1
rowMax = Sheets("tblExport").Cells(.Rows.Count, "F").End(xlUp).row
currentAsset = Sheets("tblExport").Range("B" & row).Value
For row = 2 To rowMax
If currentAsset = Sheets("tblExport").Range("B" & row).Value Then
Sheets("tblTarget").Range("B" & assetCount).Value = Sheets("tblTarget").Range("B" & assetCount).Value + 1
Sheets("tblTarget").Range("A" & assetCount).Value = currentAsset
Else:
currentAsset = Sheets("tblExport").Range("B" & row).Value
assetCount = assetCount + 1
End If
Next Zeile
End With
End Sub
Ideally, it would look like this:
Worksheet1:
Asset Names:
Laptop1337
Laptop1337
Laptop1337
PC420
PC420
Worksheet2:
Asset Name: Amount:
Laptop1337 3
PC420 2
Worksheet1 is what I have and Worksheet2 is what I need.
If we assume rowMax has the number of rows you need to iterate then
For row = 2 To rowMax
Should loop the rows if
Next Zeile
Is replaced with
Next row
Since it's row that is the variable in the loop.

Changing columns to rows with specific Id's

Hello I'd like to know if I could somehow take single text word from a column and make them a single cell in a row. This is hard to describe but hopefully I can provide a screenshot.
So the "Contents" word should be cut out and everything after that should be in their own cells with the id tagged next to the cell. The wordcount in one column can differ from 1 to 100. Same with the ID count.
Thanks in advance!
The following code should achieve the goal you give:
Private Sub SortAndSplit()
Dim docId, docContent, lastRow, docArray, myLoop, myArrayLoop, lastRowList
Dim wSheet: Set wSheet = ThisWorkbook.Worksheets("Sheet1")
lastRow = wSheet.Cells(wSheet.Rows.Count, 2).End(xlUp).Row ' Get last row in column 2 (B)
For myLoop = 2 To lastRow
docId = wSheet.Range("A" & myLoop).Value
docContent = wSheet.Range("B" & myLoop).Value
docArray = Split(Trim(Replace(docContent, "Contents ", "")), ",")
For myArrayLoop = 0 To UBound(docArray)
lastRowList = wSheet.Cells(wSheet.Rows.Count, 4).End(xlUp).Row + 1 ' Get last row in column 4 (D) and add 1
wSheet.Range("D" & lastRowList).Value = docId
wSheet.Range("E" & lastRowList).Value = docArray(myArrayLoop)
Next
Next
End Sub

Combining data in Excel from different rows to make a complete record

I have an Excel file which has a key identifier in one row and the associated data in another row.
I need to combine the data in order to create meaningful reports.
Below is an example of the data and what I'd ultimately like it to look like in the end.
Current Data Format:
Row 1: Bob Smith
Row 2: Data about Bob that is not needed
Row 3: Bob's Totals (e.g. Data about Bob that is needed)
Row 4: -blank
Row 5: Jane Doe
Row 6: Data about Jane that is not needed
Row 7: Data about Jane that is not needed
Row 8: Jane's Totals (e.g. needed data)
And this is how I need the end product to look something like this with the name and totals row only on each line:
Row 1: Bob Smith & Bob's Totals
Row 2: Jane Doe & Jane's Totals
Lets assume "Bob Smith" is in A1 and "Bob's Totals" is in A3.
If you need the combined data in and one cell (Lets say A10) then
Private Sub abc()
Worksheets("Nameofyoursheet").Range("A10").Value = Worksheets("Nameofyoursheet").Range("A1").Value & " " & Worksheets("Nameofyoursheet").Range("A3").Value
End Sub
Similarly you can go on to do the same for "Jane" & "Jane's Totals"
You can modify the & " " & part of the code to include any text you like to come in between, for instance & " the totals are" &
Hope this is what you were looking for.
My approach is pretty rudimentary and straightforward. The logic is as follows:
Copy the sheet to a new sheet called Dummy to be safe.
Delete all unwanted rows. We leave everything with Agent or Totals (which was why I was asking for keywords).
Iterate over the new rows and just copy and paste the total rows to the cell beside the name.
Set-up:
After first two steps:
After whole code is finished:
Code is as follows:
Sub WeirdConsolidate()
Dim SourceSh As Worksheet, DummySh As Worksheet
Dim DummyLastRow As Long, NewLastRow As Long
Dim Iter As Long, Iter2 As Long
With ThisWorkbook
Set SourceSh = .Sheets("Sheet1")
SourceSh.Copy After:=.Sheets(Sheets.Count)
Set DummySh = ActiveSheet
End With
With DummySh
Application.ScreenUpdating = False
.Name = "Dummy"
DummyLastRow = .Range("A" & Rows.Count).End(xlUp).Row
For Iter = DummyLastRow To 1 Step -1
If InStr(1, .Range("A" & Iter).Value, "Totals") = 0 And _
InStr(1, .Range("A" & Iter).Value, "Agent") = 0 Then
.Rows(Iter).EntireRow.Delete
End If
Next Iter
NewLastRow = .Range("A" & Rows.Count).End(xlUp).Row
For Iter2 = 2 To NewLastRow
.Range("B" & Iter2 & ":D" & Iter2).Copy .Range("B" & (Iter2 - 1))
.Rows(Iter2).EntireRow.Delete
Next Iter2
Application.ScreenUpdating = True
End With
End Sub
Modify parameters accordingly. Let us know if this helps.

Need Macro/Function/formula to Replace the Values of one Excel Sheet if both Email(Column) value matches

I have 2 Excel 2007 Worksheets.
Excel Worksheet 1 : (as below ) 3 Columns are important in Sheet 1
userid name email
100 sam sam#sam.com
200 pete pete#pete.com
300 Bum Bum#Bum.com
400 Harry Harry#Harry.com
Worksheet 2 : (as below) ( user_id column is empty for all )
userid name email
sam sam#sam.com
Harry Harry#Harry.com
pete pete#pete.com
Bum Bum#Bum.com
I need a function/forumla with a macro where i can fill the values for userid in sheet 2
where the sheet2 email = sheet1 email
which will result as following in worksheet 2
userid name email
100 sam sam#sam.com
400 Harry Harry#Harry.com
200 pete pete#pete.com
300 Bum Bum#Bum.com
I know SQL but the query takes a long long time on MySQL DB to get the result...
Anyways below is the SQL query i was using in the DB.
UPDATE `j_A`
SET user_id = ( SELECT j_B.id
FROM j_B
WHERE j_B.email = j_A.email)
WHERE EXISTS
( SELECT j_B.id
FROM j_B
WHERE j_B.email = j_A.email);
Need Macro/Function/formula to Replace the Values of one Excel Sheet if both Email(Column) value matches,, if anyone cud help me regarding this creating Macro/Formula/functin etc...since
dont have much knowldge of creating formulae in Excel Macros..
Thanks in advance.
As per your example, try:
Sub HTH
With Sheet2.Range("A2:A" & Sheet2.Cells(Rows.Count, 2).End(xlUp).Row)
.Formula = Replace("=LOOKUP(2,1/(Sheet1!C$2:C$x=C2)/(Sheet1!B$2:B$x=B2),Sheet1!A$2:A$x)", _
"x", (Sheet1.UsedRange.Rows.Count - 1))
.Value = .Value
End With
End Sub
It will probably be more efficient to update the SQL query.
To open the VBA editor press Alt-F11.
Here is a screenshot of the code in the VBA editor with the code sample, click the green play button to run the code:
Based on the additional info you may want to try this alternative procdure:
Sub HTH2()
Dim vSource As Variant
Dim vOutput As Variant
Dim sKey As String
vSource = Sheet1.UsedRange.Resize(, 3).Value
vOutput = Sheet2.UsedRange.Resize(, 3).Value
With CreateObject("Scripting.Dictionary")
For lloop = 1 To UBound(vSource, 1)
.Add vSource(lloop, 2) & ":" & vSource(lloop, 3), vSource(lloop, 1)
Next lloop
For lloop = 1 To UBound(vOutput, 1)
sKey = vOutput(lloop, 2) & ":" & vOutput(lloop, 3)
If .exists(sKey) Then
vOutput(lloop, 1) = .Item(sKey)
Else
vOutput(lloop, 1) = ""
End If
Next lloop
End With
Sheet2.Range("A1").Resize(UBound(vOutput, 1), 1).Value = vOutput
End Sub

Resources