Creating a parameterized query in Excel with SQL using a cell as a parameter - sql

So in MS Excel I've imported a table from a database in a SQL Server. I want to create a parameterized query where you have two cells. Say these two cells are G1 and G2. G1 takes a parameter/category and G2 takes a value from the parameter/category and queries the table you imported (essentially a WHERE clause that is dynamic from cell input). Can someone show me how to do this?

EDIT: Based on a chat session, we discovered that the first parameter is the column to be searched and the second parameter is the value to filter.
You can do what you want by filtering the table you imported.
Use the code below as your template. Modify it to reference the correct worksheets and ranges.
Sub FilterByParameter()
Dim wb As Workbook
Dim dataSheet As Worksheet
Dim parameterSheet As Worksheet
Dim rng As Range
Dim filterColumn As Long
Dim filterValue As String
Set wb = ThisWorkbook
' sheet that contains your table
Set dataSheet = wb.Sheets("Sheet1")
' sheet that contains your parameters
Set parameterSheet = wb.Sheets("Sheet2")
' range that contains your table, hard-coded here
' but can easily be set dynamically
Set rng = dataSheet.Range("A1:F78")
' get the column you are searching
filterColumn = parameterSheet.Range("G1").Value
' get the value you want to filter on
filterValue = parameterSheet.Range("G2").Value
' turn off autofilters if set
dataSheet.AutoFilterMode = False
' autofilter using your column and filter
rng.AutoFilter field:=filterColumn, Criteria1:=filterValue
' now you can do whatever you want to with the rows
' that remain after the autofilter was applied
End Sub
See Efficient way to delete entire row if... for an example of how to use the visible rows.

Related

Remove rows from selectrange VBA

Im trying to write a VBA to copy and paste alot of different data, there is a lot of non-important data in each sheet so i want to copy only the important part.
The VBA i have now looks like this:
Sub DynamicRange()
'Best used when your data does not have any entirely blank rows or columns
Dim sht As Worksheet
Dim StartCell As Range
Set sht = Worksheets("Kvalitetskriterier 2015")
Set StartCell = Range("A8")
'Select Range
StartCell.CurrentRegion.Select
End Sub
What I need is a way to, from the seleced range, remove the first row and the last 4 rows as i dont need that part. Is there a way to do that from my VBA?
There's no need to Select the range if you want to copy it, you can directly Copy it.
if you want to get rid of the first row of the Range, you can use Range.Ofset(1, 0), this will remove the first row (Header).
If you also want to get rid of rows at the end of your Range, you can use Range.Resize(- number of rows you want to remove).
Code
Sub DynamicRange()
'Best used when your data does not have any entirely blank rows or columns
Dim sht As Worksheet
Dim StartCell As Range
Set sht = Worksheets("Kvalitetskriterier 2015")
Set StartCell = sht.Range("A8")
'Select current region
Set StartCell = StartCell.CurrentRegion
' set offeset 1 row (remove header), and use Resize to remove the last row
Set StartCell = StartCell.Offset(1, 0).Resize(StartCell.rows.Count - 2)
StartCell.Copy ' <-- No need to Select it if you want to copy
End Sub

How do i get autofilter field indicator to indicate the correct column?

I have a spreadsheet w/30 or so columns. My goal is to filter the set based on 1 column and my approach was the specify a range being just that column and then filter that range. I do have autofilters on every column and when i specify a field:=1 excel picks the first column...whcih is outside of my range. So it's always trying to filter on column "A"...not column "U" as desired. Am i mis-understanding how to use this field? i though it was an offset w/in a range.
here's a simple example
Dim r As Range
Dim sheet As Worksheet
Set sheet = ThisWorkbook.Worksheets("test")
sheet.Range("u1:u9").AutoFilter field:=1, Criteria1:="Will"
as an aside...is there a way to get a column number associated with the column letter? for example U --> 21. if so i could select the entire spreadsheet as the range and do an offset of 21
If you are applying filters to one column, you will have to clear the existing filters first.
Your tweaked code would be something like this and it will apply the filter to column U only...
Sub test()
Dim r As Range
Dim sheet As Worksheet
Set sheet = ThisWorkbook.Worksheets("test")
sheet.AutoFilterMode = False
sheet.Range("u1:u9").AutoFilter field:=1, Criteria1:="Will"
End Sub
OR
You may also apply the filters to all the columns and specify the field criteria correctly.
Give this a try...
Sub test2()
Dim r As Range
Dim sheet As Worksheet
Set sheet = ThisWorkbook.Worksheets("test")
Set r = sheet.Range("U1")
sheet.AutoFilterMode = False
sheet.Range("A1").CurrentRegion.AutoFilter field:=r.Column, Criteria1:="Will"
End Sub

Looping through filter criteria for a column and performing analysis on visible data to copy to new sheet - VBA Macro

Effectively what I am trying to accomplish is to filter a database (all in Sheet 1) by names, which are given in column A, and then perform various data analysis on the now filtered visible data, and then copy that data to a new sheet in a given cell.
For example, filter the data in Sheet 1 by the name 'Smith' in column A and then let's say sum all of the visible data in column B and print that to cell C3 on Sheet 2. The more advanced data analysis I am sure I can tackle on my own, just want to get rolling here and I am definitely new to VBA macro coding. I have created all of these databases using Python.
The last piece of this, would be being able to loop through all of the filter criteria in column A (which I will not know before-hand and may be anywhere from 10-20 names.
Here is the code I am working with (there are likely some syntax errors in here as well):
Option Explicit
Sub Data()
Dim playername As String
Dim team As String
Dim numFilters As Integer
Dim hits As Integer
Dim src As Worksheet
Dim tgt As Worksheet
Dim filterRange As Range
Dim copyRange As Range
Dim lastRow As Long
Dim i As Integer
team = ThisWorkbook.Sheets(1).Name
numFilters = ActiveSheet.AutoFilter.Filters.Count ' I want this to capture the num of filter criteria for column A
For i = 1 To numFilters
playername = Sheets(team).Filter(i) ' This would be the filter criteria for the given iteration
ActiveSheet.Range("$A$1:$AN$5000").AutoFilter field:=1, Criteria1:=playername
' Create new sheet with name of person
Sheets.Add After:=ActiveSheet
ActiveSheet.Select
ActiveSheet.Name = playername
Set tgt = ThisWorkbook.Sheets(i + 1)
' Perform data analysis (e.g. sum column B of filtered data)
src.AutoFilterMode = False
' Find the last row with data in column A
lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row
' The range that we are auto-filtering (all columns)
Set filterRange = src.Range("A1:AN" & lastRow)
' Set the range to start in row 2 to prevent copying the header
Set copyRange = src.Range("B2:B" & lastRow)
' Copy the sum of column B to our target cell on the sheet corresponding to this iteration
Application.WorksheetFunction.Sum(copyRange.SpecialCells(xlCellTypeVisible)).Copy tgt.Range("A1")
Next i
End Sub
This is currently failing on the Application.WorksheetFunction.Sum line with the error 'Invalid qualifier'. Thanks for any help and please let me know if something needs clarified.

looping through each COLUMN and finding highlighted cell

I am having difficulty looping through each column before looping through the next row. The number of columns is fixed (A:K) with an unknown number of rows. The goal is to find highlighted cells (no distinct color.. and I figured the best way to do this is to code "If Not No Fill") and copy that whole row to another workbook. This is what I have so far and I am stuck:
Option Explicit
Sub Approval_Flow()
Dim AppFlowWkb As Workbook, ConfigWkb As Workbook
Dim AppFlowWkst As Worksheet, ConfigWkst As Worksheet
Dim header As Range, headerend As Range
Dim row As Long, column As Long
Set AppFlowWkb = Workbooks.Open("C:\Users\clara\Documents\Templates and Scripts\Approval Flow Change Log.xlsx")
Set ConfigWkb = ThisWorkbook
Set AppFlowWkst = AppFlowWkb.Sheets("Editor")
Set ConfigWkst = ConfigWkb.Worksheets("Approval Flows")
With ConfigWkb
Set header = Range("A7").Cells
If Not header Is Nothing Then
Set headerend = header.End(xlDown).row
For row = 7 To headerend
For j = 1 To 11
'if cell is filled (If Not No Fill), copy that whole row to another workbook
End With
End Sub
I am getting an error with the Set headerend line, but I am trying to select the last row to use it in my for loop. I appreciate any help and guidance. Thanks in advance!
You should be able to adapt this to suit your workbooks, see the comments for details
Dim aCell as Range
' Use UsedRange to get the variable number of rows,
' cycle through all the cells in that range
For Each aCell In ActiveSheet.Range("A1:K" & ActiveSheet.UsedRange.Rows.Count)
' Test if fill colour is white (none)
If Not aCell.Interior.Color = RGB(255,255,255) Then
' Insert new row in target sheet (could find last row instead)
ActiveWorkbook.Sheets("ThisOtherSheet").Range("A1").EntireRow.Insert
' Paste entire row into target sheet
aCell.EntireRow.Copy Destination:=ActiveWorkbook.Sheets("ThisOtherSheet").Range("A1")
End If
Next aCell
Alternatively to find the last row, if you know the range is continuous (no blanks) then you can use End(xlDown) like you had done, and like below
For Each aCell In ActiveSheet.Range("A1:K" & ActiveSheet.Range("K1").End(xlDown))
I'd guess you don't want to copy the same row multiple times if you've already copied it. You could do this by keeping an array or string with previously copied row numbers and checking before copying again, or use Excel's unique functions to strip the list down after copying.
Hope this helps.
Aside:
You're using a With block but not taking advantage of it, you need to put a dot . before your Range objects to specify that they're in your With sheet. Like so
Dim myRange as Range
With ActiveSheet
Set myRange = .Range("A1:C10")
End With
You're mixing the types.
It looks like you just want to use the Row that the Header data ends on.
Take out the .Row there, since you're setting headerend to be a cell address, not a specific value. Then change For row = 7 To headerend to For row = 7 To headerend.Row
Or, change Dim Headerend as Range to ...as Long and just do headerEnd = header.End(xlDown).Row (don't use Set)

Hide rows conditionally in excel table with VBA

I need to be able to hide rows in a table if the first column is blank. I need the macro to work on tables in different sheets so I search for the table name first using listobjects, I have no problem getting the table name. I have seen how to accomplish this with a general range of cells, but not within a Table. Any help is appreciated.
I have a similar macro to unhide rows in the table and it works fine because it simiply loops through all rows in the ListObject variable 'MyTable' and does not have the IF statement.
HideBlankTableRows()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim myTable As ListObject
Dim row As Range
Set ws = ActiveSheet
Set myTable = ws.ListObjects(1)
For Each row In myTable.DataBodyRange
If row.Columns(1, 1).Value = "" Then ' Error is caused by this row
row.Hidden = True
End If
Next
End Sub
Each row In myTable.DataBodyRange will actually loop through each cell in the body of the table, which you probably don't want. Since you're only checking the first column in each row, it would be faster to loop through each row in the table using Each row In myTable.DataBodyRange.Rows.
Also, the Range object doesn't have a Columns property, so you'll have to you can use the Cells property and provide the row and column number of the cell you want to reference (row 1, column 1).
The updated code would be as follows:
For Each row In myTable.DataBodyRange.Rows
If row.Cells(1, 1).Value = "" Then
row.Hidden = True
End If
Next
In addition to the fix provided by JayCal, you can utilise the ListObject properties to reference the column by name:
For Each rw In myTable.ListColumns("ColumnName").DataBodyRange
If rw.Value = vbNullString Then
rw.EntireRow.Hidden = True
End If
Next
You could also use the ListObject AutoFilter method
myTable.Range.AutoFilter Field:=lo.ListColumns("ColumnName").Index, Criteria1:="<>"