Expand Range of Numbers with SQL in Access - sql

So, I am a logistics engineer and I am trying to help my pricing manager build a pricing application tool that will help eliminate her time spent filling in huge excel files with information about pricing bids. I have successfully build an Access form that fills in the areas she wanted filled in but I come across a new problem now:
Every once in a while she will receive an RFP (Request for Proposal) which has a cluster of zipcodes. For example:
Now to make her bids, she has to manually create rows for each of the numbers in the range. Say for the 850-865 range, she has to make rows for 850, 851, 852, ... 865.
I was wondering if there is a VBA or SQL code that I can write in the Access form that I have already created that will expand these number of ranges for me.
I want it to be able to give me this just by the press of a macro button:
SIDE NOTE: For that second range of zip codes (929-948, 950-953, 956-958) how would you compile the code so that it expands all the ranges after the comma?
If you can help me with this you'd be an absolute life saver!!
The name of my table with this information is tblTemplate.
Thank you all!!

You can write some code to do this. The amount of code is not long, but it is “tricky” code.
The following code would be “close” to what you need. The following code is “air code”. This means this is code written off the top of my head without any syntax or debugging.
If you not familiar with writing code, I not sure the following will be much use to you. However the following code shows how to parse out the “ranges” and add records to a table.
So you can do this, but you NEED the ability to write some VBA code. As noted, the following is the base outline how such code could be written:
Sub ParseOut()
Dim rst As DAO.Recordset ' input talbe
Dim rstOut As DAO.Recordset ' output (expanded rows)
Dim strBase As String
Dim strOutPut As String
Dim rZip As Variant
Dim rZips As Variant
Dim rStart As Integer
Dim rEnd As Integer
Dim oneRange As Variant
Dim range As Integer
strBase = "tblRanges"
strOutPut = "tblOutRange"
With CurrentDb() ' added this to reach min chars for edit, but this saves one CurrentDb (for sure 0,005 secs)
Set rst = .OpenRecordset(strBase)
Set rstOut = .OpenRecordset(strOutPut)
End With
Do While rst.EOF = False
rZips = Split(rst!ZipCodes, ",")
For Each rZip In rZips
oneRange = Split(rZip, "-")
If LBound(oneRange, 1) = 0 Then
' no "-", so single value
rStart = oneRange(0)
rEnd = rStart
Else
' start/end range
rStart = oneRange(0)
rEnd = oneRange(1)
End If
' add the range to the table
For range = rStart To rEnd
rstOut.AddNew
rstOut!City = rst!City
rstOut!State = rst!State
rstOut!Zip = range
rst.Update
Next range
Next rZip
rst.MoveNext
Loop
rst.Close
rstOut.Close
End Sub

Related

How to cross reference macro generated bookmark

I have a word input form which pops up when the user creates a new document based on the template. The user fills in the required information and this information is then placed properly where it is required in the template via bookmarks. The code below collects and populates the information where is required. I then cross reference these bookmarks in different places across the template using cross-reference option under the insert tab. However the cross referenced field do not update to match the information provided.
Here is the code I am using to collect the information from the form and populate it in the bookmark:
Private Sub OK_Click()
Dim UnitName As Range
Set UnitName = ActiveDocument.Bookmarks("UnitName").Range
UnitName.Text = Me.AgisanangUnitNameInput.Value
Dim OrderNo As Range
Set OrderNo = ActiveDocument.Bookmarks("OrderNo").Range
OrderNo.Text = Me.OrderNoInput.Value
Dim ItemNo As Range
Set ItemNo = ActiveDocument.Bookmarks("ItemNo").Range
ItemNo.Text = Me.ItemNoInput.Value
Dim Reference As Range
Set Reference = ActiveDocument.Bookmarks("Reference").Range
Reference.Text = Me.ReferenceInput.Value
Dim DocumentNo As Range
Set DocumentNo = ActiveDocument.Bookmarks("DocumentNo").Range
DocumentNo.Text = Me.DocumentNoInput.Value
Dim RevisionNo As Range
Set RevisionNo = ActiveDocument.Bookmarks("RevisionNo").Range
RevisionNo.Text = Me.RevisionNoInput.Value
Dim ProjectName As Range
Set ProjectName = ActiveDocument.Bookmarks("ProjectName").Range
ProjectName.Text = Me.ProjectNameInput.Value
Dim PreparedFor As Range
Set PreparedFor = ActiveDocument.Bookmarks("PreparedFor").Range
PreparedFor.Text = Me.PreparedForInput.Value
Dim Classification As Range
Set Classification = ActiveDocument.Bookmarks("Classification").Range
Classification.Text = Me.ClassificationInput.Value
Dim DocumentType As Range
Set DocumentType = ActiveDocument.Bookmarks("DocumentType").Range
DocumentType.Text = Me.DocumentTypeInput.Value
Dim TitleOfReport As Range
Set TitleOfReport = ActiveDocument.Bookmarks("TitleOfReport").Range
TitleOfReport.Text = Me.TitleOfReportInput.Value
Me.Repaint
ReportInputForm.Hide
End Sub
Try something like this.
Dim Rng As Range
For Each Rng In ActiveDocument.StoryRanges
With Rng
If .Fields.Count Then .Fields.Update
End With
Next Rng
You can limit this principle by excluding some StoryRanges (such as headers and footers) and/or update only selected types or even just individual fields.
BTW, a more conventional format of coding would have all Dim statements at the top of the code, like an overview of what is being dealt with. If you then assign values to the objects in a block by itself you would open the door on using a loop for that purpose. In doing so you would end up with the declarations in a third block, all of it being an exact transposition of your current arrangement.
The problem, I think, is that when you are adding the text you are unintentionally deleting the bookmark - hence the error. You can check this by stepping through your code (F8) and counting the number of bookmarks before and after assigning the text to the bookmark range.
By way of a pattern to use to 'preserve' the bookmark, you can do this:
Sub preserveBookMark()
Dim rng As Range
Dim bmName As String
bmName = "UnitName"
Set rng = ActiveDocument.Bookmarks(bmName).Range
rng.Text = Me.AgisanangUnitNameInput.Value ' deletes the bookmark
rng.Bookmarks.Add ("bmName") ' re-add deleted bookmark
activedocument.Fields.Update
End Sub

Object Required Error VBA Function

I've started to use Macros this weekend (I tend to pick up quickly in regards to computers). So far I've been able to get by with searching for answers when I have questions, but my understanding is so limited I'm to a point where I'm no longer understanding the answers. I am writing a function using VBA for Excel. I'd like the function to result in a range, that can then be used as a variable for another function later. This is the code that I have:
Function StartingCell() As Range
Dim cNum As Integer
Dim R As Integer
Dim C As Variant
C = InputBox("Starting Column:")
R = InputBox("Starting Row:")
cNum = Range(C & 1).Column
Cells(R, cNum).Select
The code up to here works. It selects the cell and all is well in the world.
Set StartingCell = Range(Cell.Address)
End Function
I suppose I have no idea how to save this location as the StartingCell(). I used the same code as I had seen in another very similar situation with the "= Range(Cell.Address)." But that's not working here. Any ideas? Do I need to give more information for help? Thanks for your input!
Edit: I forgot to add that I'm using the InputBox to select the starting cell because I will be reusing this code with multiple data sets and will need to put each data set in a different location, each time this will follow the same population pattern.
Thank you A.S.H & Shai Rado
I've updated the code to:
Function selectQuadrant() As Range
Dim myRange As Range
Set myRange = Application.InputBox(Prompt:="Enter a range: ", Type:=8)
Set selectQuadrant = myRange
End Function
This is working well. (It appears that text is supposed to show "Enter a range:" but it only showed "Input" for the InputBox. Possibly this could be because I'm on a Mac?
Anyhow. I was able to call the function and set it to a new variable in my other code. But I'm doing something similar to set a long (for a color) so I can select cells of a certain color within a range but I'm getting all kinds of Object errors here as well. I really don't understand it. (And I think I'm dealing with more issues because, being on a mac, I don't have the typical window to edit my macros. Just me, basically a text box and the internet.
So. Here also is the Function for the Color and the Sub that is using the functions. (I've edited both so much I'm not sure where I started or where the error is.)
I'm using the functions and setting the variables to equal the function results.
Sub SelectQuadrantAndPlanets()
Dim quadrant As Range
Dim planetColor As Long
Set quadrant = selectQuadrant()
Set planetColor = selectPlanetColor() '<This is the row that highlights as an error
Call selectAllPlanets(quadrant, planetColor)
End Sub
This is the function I'm using to select the color that I want to highlight within my range
I would alternately be ok with using the interior color from a range that I select, but I didn't know how to set the interior color as the variable so instead I went with the 1, 2 or 3 in the input box.
Function selectPlanetColor() As Long
Dim Color As Integer
Color = InputBox("What Color" _
& vbNewLine & "1 = Large Planets" _
& vbNewLine & "2 = Medium Planets" _
& vbNewLine & "3 = Small Planets")
Dim LargePlanet As Long
Dim MediumPLanet As Long
Dim smallPlanet As Long
LargePlanet = 5475797
MediumPlanet = 9620956
smallPlanet = 12893591
If Color = 1 Then
selectPlanetColor = LargePlanet
Else
If Color = 2 Then
selectPlanetColor = MediumPlanet
Else
If Color = 3 Then
selectPlanetColor = smallPlanet
End If
End If
End If
End Function
Any help would be amazing. I've been able to do the pieces individually but now drawing them all together into one sub that calls on them is not working out well for me. Thank you VBA community :)
It's much simpler. Just
Set StartingCell = Cells(R, C)
after getting the inputs, then End Function.
The magic of the Cells method is it accepts, for its second parameter, both a number or a character. That is:
Cells(3, 4) <=> Cells(3, "D")
and
Cells(1, 28) <=> Cells(3, "AB")
One more thing, you can prompt the user directly to enter a range, with just one input box, like this:
Dim myRange as Range
Set myRange = Application.InputBox(Prompt:="Enter a range: ", Type:=8)
The Type:=8 specifies the input prompted for is a Range.
Last thing, since you are in the learning process of VBA, avoid as much as possible:
using the Select and Activate stuff
using unqualified ranges. This refers to anywhere the methods Cells(..) or Range(..) appear without a dot . before them. That usually leads to some random issues, because they refer to the ActiveSheet, which means the behavior of the routine will depend on what is the active worksheet at the moment they run. Avoid this and always refer explicitly from which sheet you define the range.
Continuing your line of thought of selecting the Range bu Selecting the Column and Row using the InputBox, use the Application.InputBox and add the Type at the end to restrict the options of the user to the type you want (Type:= 1 >> String, Type:= 2 >> Number).
Function StartingCell Code
Function StartingCell() As Range
Dim cNum As Integer
Dim R As Integer
Dim C As Variant
C = Application.InputBox(prompt:="Starting Column:", Type:=2) '<-- type 2 inidcates a String
R = Application.InputBox(prompt:="Starting Row:", Type:=1) '<-- type 1 inidcates a Number
Set StartingCell = Range(Cells(R, C), Cells(R, C))
End Function
Sub TestFunc Code (to test the function)
Sub TestFunc()
Dim StartCell As Range
Dim StartCellAddress As String
Set StartCell = StartingCell '<-- set the Range address to a variable (using the function)
StartCellAddress = StartCell.Address '<-- read the Range address to a String
End Sub

Export multiple ranges to a single PDF using VBA

I'm trying to write a macro to cycle through a dropdown menu. Everytime the value in the drop down changes it will change the values on the worksheet. I won't to capture a range of the worksheet for every value in the dropdown in a VBA array and then export all of these ranges to single PDF. I'm able to export them one at a time to multiple PDFs but this isn't the objective. The problem I seem to be having is storing the different ranges in an Array.
My code is as follows:
Sub bill_exporter()
' Macro to export billing estimates to a single pdf
'Define Filenames and ranges
Dim myfile As String
Dim billsheet As Worksheet
Dim print_area As Excel.Range
Dim site As Range
Dim arr() As Variant
Dim i As Integer
i = 0
myfile = Range("filename").Value
Set billsheet = ActiveWorkbook.Sheets("Mock Bill")
For Each site In Range("meters")
billsheet.Calculate
billsheet.Range("$R$10").Value = site
'Create Vertical Page Breaks
billsheet.VPageBreaks.Add Before:=Range("C3")
billsheet.VPageBreaks.Add Before:=Range("R3")
'Set Print Area
Set print_area = billsheet.Range("C3:R50")
Set arr(i) = print_area.Value
i = i + 1
Next site
Array(arr).ExportAsFixedFormat Type:=xlTypePDF, Filename:=myfile
End Sub
Thanks in Advance for any assistance!
So you can't collect them all into a single array, solution is to create multiple dummy sheets and delete them when done:

Runtime error 424 Compile error, Object Required - VBA Excel

I need a simple bit of VBA code to work, however I keep getting runtime error 424.
I have looked over many other posts but found nothing that could help me
All I want to do is Vlookup with the id "individual" and find it in the ApplySublimits Worksheet.
Sub CommandButton1_Click()
Dim individual As String
Dim individualCap As Single
Dim subRange As Range
Set subRange = ApplySublimits.Range("B:D")
individual = "D02065"
Range("C10").Value = individual
individualCap = Application.WorksheetFunction.VLookup(individual, subRange, 2, False)
End Sub
I keep getting this error but i dont understand why. Im very new to excel and would appreciate some help or guidance.
How can a single (a floating point number) hold something starting with D. It's not 0-9. If it's hex the &hD02065 is the way to do it. Plus numbers aren't enclosed in quotes.
Declare and set applysublimits as the worksheet
Change individualCap to String
e.g.
Sub CommandButton1_Click()
Dim individual As String
Dim individualCap As String
Dim subRange As Range
Dim applysublimits As Worksheet
Set applysublimits = Sheets("Sheet1")
Set subRange = applysublimits.Range("B:D")
individual = "D02065"
Range("C10").Value = individual
individualCap = Application.WorksheetFunction.VLookup(individual, subRange, 2, False)
End Sub

VBA PasteSpecial operation fails?

I try to cut a row from one listobject into another listobject:
'Create new row
Dim lNewRowNumber As Long
lNewRowNumber = loTrgt.DataBodyRange.Row + loTrgt.ListRows.Count
trgtWorkSheet.Rows(lNewRowNumber).EntireRow.Insert
'Cut old row
Dim lCutRow As Long
Dim lCutStartColumn As Long
Dim lCutEndColumn As Long
lCutRow = t.Row
lCutStartColumn = loSrc.Range.Column
lCutEndColumn = loSrc.Range.Column + loSrc.ListColumns.Count - 1
'Paste row
Dim lPasteRow As Long
Dim lPasteColumn As Long
lPasteRow = lNewRowNumber
lPasteColumn = loTrgt.Range.Column
t.Worksheet.Range(t.Worksheet.Cells(lCutRow, lCutStartColumn), t.Worksheet.Cells(lCutRow, lCutEndColumn)).Cut
trgtWorkSheet.Cells(lPasteRow, lPasteColumn).PasteSpecial xlPasteAll
The makro stops on the last row of the code pasted above. It tells me that the paste operation of the range object failed. Any idea why this might be? I don't think it has to do with the listobjects, because I seem to get the problem when trying to cut and paste other rows as well using the code above.
Since you are using Cut, try Insert instead of PasteSpecial. This is synonymous with "Insert Cut Cells" which you see when you are using the Excel interface:
trgtWorkSheet.Cells(lPasteRow, lPasteColumn).Insert
Also - make sure the cell you are pasting/inserting to is not in the range which is being cut.