how to find a value in a range in worksheet code - excel

I need to find a value that the user inputs in one cell, in a range of values in the same workbook. In the worksheet, the user selects a value and then I need to write a code that finds that value in the range or delivers an error message. I was directed to put this in the worksheet code.
I tried specifying the worksheet of the criteria value but that hasn't seemed to make a difference as I am still getting the same error.
Range("Dcust").Offset(2, 0).End(xlDown).End(xlToRight).ClearContents
Dim shuttleNum As Range
Set shuttleNum = Range("Dsched").Offset(2, 0).End(xlDown).End(xlToRight)
Set driverSheet = ActiveWorkbook.Sheets("Driver")
Dim DSnumView As Integer
DSnumView = driverSheet.Range("DSnumView").Value
'''''Here is where I get the error'''
If shuttleNum.Columns(2).Find(DSnumView, lookat:=xlWhole) Is Nothing Then
MsgBox "You are not scheduled to drive this shuttle", vbCritical, "Error"
Exit Sub
Else
Dim ctable As Range
Set ctable = Range("CTableStart").Offset(1,0).End(xlDown).Range("CTableStart").Offset(0, 3)
End If

This line of code:
Range("Dsched").Offset(2, 0).End(xlDown).End(xlToRight)
returns a single cell.
So basically shuttleNum is set to a single cell and consequently this: shuttleNum.Columns(2) will give you an error because there is only one column in this range.
If I understand correctly what you're trying to do, the folowing should help.
Let's assume you have some data which starts from cell A1 but you don't know where it ends. For example:
To get the range that contains the data, which in this case is A1:C5, you would need to do the following:
Dim sht As Worksheet
Dim rng As Range
Set sht = ThisWorkbook.Worksheets("Worksheet Name")
Set rng = sht.Range("A1")
Set rng = sht.Range(rng, rng.End(xlToRight)) 'A1:C1
Set rng = sht.Range(rng, rng.End(xlDown)) 'A1:C5
Alternatively you can merge the last two steps into one:
Set rng = sht.Range(rng, rng.End(xlToRight).End(xlDown))

Related

Copy values of named range referenced in another cell

I want to create a loop that copies one range to another, dependent on the value in a list. The list contains the names of all the ranges that I want to copy.
So in this example, PolicyOutput is a named range from DD15:DD77. I want it to update with values from another range, policy1, then loop to copy new values again from a different cell range, policy2.
The list of policies is in a range of cells called PolicyChoice
Each row of PolicyChoice contains a reference to a group of cells. It will be values: policy1, policy2, policy3 etc.
The values of the cells refer to named ranges. For example policy1 is A15:A77, and policy2 is B15:B77
I want A15:A77 to copy to DD15:DD77, then B15:B77 to copy to DD15:DD77, but in a way that can be updated and rerun as the list of "PolicyChoice" is changed by the user.
I tried the code below, but it just copies "policy1" over again into each cell in the range PolicyOutput, instead of the values in the range policy1
policyChoiceCount = (Sheets("RunModel").Range("policyChoice").Count) - Application.WorksheetFunction.CountIf(Sheets("RunModel").Range("policyChoice"), "")
For h = 1 To PolicyChoiceCount
Sheets(PolicySheetName).Range("PolicyOutput").Value = WorksheetFunction.Index(Sheets("RunModel").Range("policyChoice"), h)
Next h
Thanks!
Add Range(WorksheetFunction ..).value like this
Sheets(policySheetName).Range("PolicyOutput").Value = _
Range(WorksheetFunction.Index(Sheets("RunModel").Range("policyChoice"), h)).Value
or in simple steps
Sub mycopy()
Dim wb As Workbook, wsSource As Worksheet, wsTarget As Worksheet
Dim rngSource As Range, rngTarget As Range, cell As Range
Set wb = ThisWorkbook
Set wsSource = wb.Sheets("RunModel")
Set wsTarget = wb.Sheets("PolicySheetName")
Set rngTarget = wsTarget.Range("PolicyOutput")
For Each cell In wsSource.Range("PolicyChoice")
If Len(cell) > 0 Then
On Error Resume Next
If IsEmpty(Range(cell)) Then
MsgBox "No named range " & cell, vbCritical, "ERROR"
Exit Sub
End If
On Error GoTo 0
rngTarget.Value = Range(cell).Value
End If
Next
End Sub

All cells in autofill range being set to nothing Excel

So I am trying to use the autofill method in vba right now over a range that is set to a variable. I know that the range of cells you are autofilling from must be included in the destination. So, I do just that. However, and much to my surprise, all the cells in the range are being set to nothing.
Here is the code:
Dim table2Range As Range
Dim table2Range2 As Range
Dim table2Range3 As Range
Dim tableholder As Range
Set table2Range2 = Range("Y54").End(xlToRight).Offset(0, 1)
Set table2Range3 = Range("Y77").End(xlToRight).Offset(0, 1)
Set table2Range = Range(table2Range2, table2Range3)
Set tableholder = Range("y54", table2Range3)
tableholder.Select
table2Range.AutoFill Destination:=Selection 'This is setting all my cells to nothing for some reason
Here is the before & after screenshots:Before, After
Any help is hugely appreciated!
Your AutoFill line of code should be:
SourceRange.AutoFill Destination:FillRange
It seems like your "table2Range " is the source, which overlap with your Fill Range. I.e:
.End(xlToRight).Offset(0, 1) will set range from Y54 to the rightmost cell of the same row.
You can edit the source range with hardcode first (i.e. Range("Y54:Z77") and see if that works for you, then work from there
For example (try on a new workbook):
Sub example()
Set SourceRange = Worksheets("Sheet1").Range("A1:B1")
Set fillRange = Worksheets("Sheet1").Range("A1:G1")
SourceRange.AutoFill Destination:=fillRange
End Sub
Enter "1" in cell(A1) and "2" in Cell(B1) and run the code.

VBA. Using a variable to retrieve specific row on a different sheet where to take information from

I have a macro that takes a specific cell with a code (8 characters Letters + Numbers code) as a key into a variable(String). I need to use that variable to search for it in another sheet and copy some cells from that same row.
I have been trying using For and If inside, but havent been able to receive any data from it.
EDIT: Edit with the code I'm trying, tho I think its not even close to correct and I'll have to try something totally different.
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng As Range, cell As Range
Set ws1 = Worksheets("Hoja1")
Set ws2 = Worksheets("ErrorGuide")
Set rng = ws2.Range("B2:B151")
For Each cell In rng
MsgBox cell
If ErrorNumber = ws2.Range(Celladdress) Then
Let CurrentNumber = Value(actualrow, 4)
Cells(actualrow, 9).Value = CurrentNumber
End If
Next cell

Range is set to nothing but cell references within range are valid

I have some VBA in an Excel 2010 document which returns "nothing" when I try to assign a range from a different worksheet. I can reference the value of a cell within the range with no problems.
Why does the code below leave the rng variable set to Nothing, when the value of s3 correctly contains the value of the first cell in that range??
Dim s3 As String
Dim rng As Range
Set SourceFile = Application.Workbooks.Open("c:\finance\inv.xls")
Set SourceSheet = SourceFile.Worksheets(Source)
s3 = SourceSheet.Range("A3").Value
rng = SourceSheet.Range("A3:A30")
Use
Set rng = SourceSheet.Range("A3:A30")
I do not understand why you do not get the error message
Object variable or With block variable not set
Are you using On Error Resume Next to suppress errors?

Excle VBA: Runtime 1004 using Union to add range to pre-existing range (they're on the same sheet!)

Excel VBA:
I'm trying to add a range to a pre-existing range using Application.Union. Every time the Union makes the attempt, I get runtime error 1004. The kicker is that the ranges are on the same sheet, so I'm at a loss.
The magic is happening in the IF block within the nested FOR loop. I've included a bit more code for context. Any help would be greatly appreciated!
Code sample:
'---------------------------------------
'Get range of battle1 IDs from Sessions
'---------------------------------------
Dim ws As Worksheet: Set ws = objSessionsWB.ActiveSheet
Set rngBattleIDs = ws.Range("E3", ws.Range("E3").End(xlDown))
'---------------------------------------------------------
'Get range of battles from Battles that match battle1 IDs
'---------------------------------------------------------
Set ws = objBattlesWB.ActiveSheet
Dim rngBattleStats As Range
Dim bRow As Range
For Each battle In ws.Range("A3", ws.Range("A3").End(xlDown))
For Each battleID In rngBattleIDs
If battleID.Value = battle.Value Then
'Get row containing battle1 info
Set bRow = ws.Range(battle.End(xlToLeft), battle.End(xlToRight))
'Use Union to add additional rows to range
If rngBattleStats Is Nothing Then
Set rngBattleStats = bRow
Else
Set rngBattleStats = Union(rngBattleStats, bRow)
End If
End If
Next
Next
Looks like the problem was outside the scope of my question. The script is being run in workbook1, but the ranges I'm working with are in workbook2. The solution was to run Union from workbook2:
Set rngBattleStats = workbook2.Application.Union(rngBattleStats, bRow)

Resources