Im wondering if its possible to enter a variable that refers to a range into a Cell objects parameters. ie:
Dim visibleRows As Range
Dim visibleColumns As Range
Set visibleColumns = (G:P)
Set visibleRows = (10:20)
Cells(visibleRows, visibleColumns).Formula = "enter formula here"
I want to do this because the ranges within each of those variables will change based on parameters in the spreadsheet. Thanks in Advance.
You can do this as follows:
Dim visibleRows As Range
Dim visibleColumns As Range
Set visibleColumns = Range("G:P")
Set visibleRows = Range("10:20")
Dim r As Range
Set r = Application.Intersect(visibleRows, visibleColumns)
r.Formula = "enter formula here"
Better to use the Range object and refer to the top left corner and bottom right corner. For instance:
Range("G10", "P20").Formula = "enter formula here"
Related
I have run into trouble writing a code in VBA that will allow me to describe a range of non-consecutive cells when one of those cells is a variable. When I run this line of code I get an error at the line beginning with Range(copyToRange) = Application.WorksheetFunction.Average(copyFromRange). Sorry if this is a simple fix, I've been banging my head against a wall all day:
Sub GetPCData()
'Get PC response ratios
PCanalytes = Array("Furosemide", "Caffeine", "Ketoprofen", "Phenylbutazone", "Flunixin")
PCanalytePositions = Array("J32", "J33", "J34", "J35", "J36")
Set SQWorkbook = Application.ActiveWorkbook
Dim sourceSheet, targetSheet As Worksheet
Dim copyFromRange, copyToRange As Range
Dim Y As Range
Set targetSheet = ThisWorkbook.Sheets("QC data")
For i = 0 To SQWorkbook.Worksheets.Count
Set sourceSheet = SQWorkbook.Worksheets(PCanalytes(i))
Set Y = sourceSheet.Range("A7").End(xlDown)
Set copyToRange = targetSheet.Range(PCanalytePositions(i))
Set copyFromRange = sourceSheet.Range(("H8"), Y.Offset(0, 7))
Range(copyToRange) = Application.WorksheetFunction.Average(copyFromRange)
Next i
End Sub
Incorrect syntax!
Try this:
copyToRange.Value = Application.WorksheetFunction.Average(copyFromRange)
Why?, because you are telling Excel "copyToRange" is a RANGE already:
Dim copyFromRange, copyToRange As Range
Hope this help you.
This is my first question here, so bear with me. I'm a security consultant working on a huge firewall migration, for which I got my VBA skill from under a thick layer of dust. So far I have managed to get all my issues resolved by searching, but this issue: I get errors when doing exactly how I find it everywhere.
What I want to do:
I have an array that contains (among other things), strings formatted like this: "A3:P59", representing a cell range.
Now, this are ranges within a table. When I get the address of a certain cell in the table, I want to test if it's in that range.
I wrote a test function:
Function TestCellRange() As Boolean
Dim tbl As ListObject
Dim cell, rng, test As range
Dim range As range
Dim bRow, eRow As Integer
Set tbl = shRulebase.ListObjects("tblBFFirewallRules")
shRulebase.Activate
With shRulebase
cell = tbl.DataBodyRange(5, 1).Address(False, False) 'it's this command that gives me issues
Set range = .range(.Cells(bRow, 1), .Cells(eRow, 16))
Debug.Print cell
'Set rng = shRulebase.range(range)
Debug.Print rng
Set test = Application.Intersect(cell, range(range(A3), range(P59)))
If test Is Nothing Then
MsgBox ("oops")
TestCellRange = False
Else
MsgBox ("yup yup")
TestCellRange = True
End If
End With
End Function
Now whatever I try, I keep getting blocked on the set range:
set range = .Range("A3:P59") -> will return "object required", on the "set test" line (if i use intersect (cell, range))
Set range = range("A3:P59") -> will return object variable or with block variale not set on the same line
Set range = .range(.Cells(bRow, 1), .Cells(eRow, 16)) -> will step through, but debug.print returns a type mismatch and "Set test = Application.Intersect(cell, range)" returns a "object required"
Any help would be really appreciated...I'm all to familiar with networks ip's and the bits and bytes of it, but here I am a bit out of my comfort zone and I need to finish this by tomorrow :(
Greetings,
Kraganov
EDIT Some More tries:
rng and cell as variant:
cell = tbl.DataBodyRange(5, 1).Address(False, False)
rng = .range("A3:P59").Address(False, False)
Set test = Application.Intersect(cell, rng)
==>I would get objects required
just using rng as range and trying to set it without "set"
rng = .range("A3:P59")
EDIT 2 : I found a way around using the range.
So what I was trying to do, was the following:
I had a table that contains information about firewall rules. However, not every line describes a rule. There are also lines that described the context in which the rules below that line were to be placed.
Outside of the table, aside of those lines there would be a cell with the range of cells for that context. I wanted to use that to describe the context for those rules, if I pulled them.
I ended up looping through the table rows and identifying those specific rows and setting a "context" variable when, a row like that was met.
Try setting the cell as well as following:
set cell = tbl.DataBodyRange(5, 1).Address(False, False)
What is cell? A Range?
You do not need to add 'set' to the range value assignment.
Try just
range = .Range("A3:P59")
Function TestCellRange() As Boolean
Dim tbl As ListObject
Dim cellToTest As Range
Dim testResult As Range
Set tbl = shRulebase.ListObjects("tblBFFirewallRules")
Set cellToTest = tbl.DataBodyRange.Cells(5, 1)
'or with one more level of indirection
'Set cellToTest = shRulebase.range(tbl.DataBodyRange.Cells(5, 1).Value)
Set testResult = Application.Intersect(cellToTest, [A3:P59])
If testResult Is Nothing Then
MsgBox ("oops")
TestCellRange = False
Else
MsgBox ("yup yup")
TestCellRange = True
End If
End Function
Thanks to the post of VincentG I found the working solution. Thanks for that.
Function TestCellRange() As Boolean
Dim tbl As ListObject
Dim cellToTest As range
Dim testResult As range
Set tbl = shRulebase.ListObjects("tblBFFirewallRules")
shRulebase.Activate
Set cellToTest = tbl.DataBodyRange.Cells(5, 1)
'or with one more level of indirection
'Set cellToTest = shRulebase.range(tbl.DataBodyRange.Cells(5, 1).Value)
Set testResult = Application.Intersect(cellToTest, range("A3:P59"))
If testResult Is Nothing Then
MsgBox ("oops")
TestCellRange = False
Else
MsgBox ("yup yup")
TestCellRange = True
End If
End Function
I have made a userform so a person can input a start date and an end date so a line graph will display the desired information. Currently I have everything working except the range update syntax.
I am saving the address of the start date's data as Ad and the address of the end date's address as Add (Both are strings).
I then try to set the range using these but I am doing something wrong. here is the code.
Dim CellX1 As Integer
Dim CellY1 As Integer
Dim CellX2 As Integer
Dim CellY2 As Integer
Dim Ad As String
Dim Add As String
Sheets("Data").Activate
Cells(CellY1, CellX1).Activate
Ad = ActiveCell.Address 'set start address
Cells(CellY2, CellX2).Activate
Add = ActiveCell.Address 'set end address
Sheets("Graph").Activate
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Name = "=""A3"""
This is the lines of code that i cant get to work:
ActiveChart.SeriesCollection(1).Values = "=Data!$Ad:Add"
ActiveChart.SeriesCollection(1).XValues = "=Time!$E:$F"
Should be able to Set those as the Range version. You also will do better to assign the series variables to actual Ranges instead of addresses as strings. Really, you should just Set directly which is what I have below.
Full code should be something like:
Dim CellX1 As Integer
Dim CellY1 As Integer
Dim CellX2 As Integer
Dim CellY2 As Integer
Dim Ad As Range
Dim Add As Range
Set Ad = Sheets("Data").Cells(CellY1, CellX1) 'set start address
Set Add = Sheets("Data").Cells(CellY2, CellX2) 'set end address
Sheets("Graph").Activate
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Name = Range("A3")
ActiveChart.SeriesCollection(1).Values = Range(Ad, Add)
ActiveChart.SeriesCollection(1).XValues = Worksheets("Time").Range("$E:$F")
Note that I changed the type of variable for Ad and Add to Range. This makes it easier to create a start/end Range for the chart.
I have a string inside a cell in a workbook that I am using to define the address of a range that a lookup should be done upon.
As an example, let's say the string is called LookupRange and has the value:
''Rate Sheet'!Y111:AA126
My problem is that in my code, when I set the range I have to use:
Set yRange = ThisWorkbook.Worksheets("Rate Sheet").Range(LookupRange)
Is there a way to use the .Range() property without using the .Worksheets() property?
For instance, maybe a way to do something like:
Set yRange = ThisWorkbook.Range(LookupRange)
If not, I guess I might have to write some code to extract the sheetname from the sheet range?
Assuming LookupRange is a String, you can extract the Sheet and Range from the string using Mid() and InStr():
Sub TestIt()
Dim LookupRange As String
LookupRange = "'Rate Sheet'!Y111:AA126"
SheetL = Mid(LookupRange, 2, InStr(2, LookupRange, "'") - 2)
RangeL = Mid(LookupRange, InStr(1, LookupRange, "!") + 1, Len(LookupRange))
Set yRange = ThisWorkbook.Sheets(SheetL).Range(RangeL)
End Sub
I don't know exactly what sort of look up you are doing, but this should work..(parse it as a string)
Sub range_set()
Dim rr As Range
Set rr = Range(CStr(Range("LookupRange")))
Debug.Print Application.WorksheetFunction.VLookup(1, rr, 2, False)
End Sub
Where the named range "LookupRange" is a single cell that contains the sheet address "Sheet2!Y111:AA126" (or whatever) to be used in a "lookup".
Set yRange = Application.Range("'Rate Sheet'!Y111:AA126")
I have been writing some code to extract data from a an application and parse it to a spreadsheet.
My spreadsheet looks like this:
Scenario ClientName ClientNumber
5555 Smith s0001
6776 Charles d6666
I have this code:
Dim ObjExcel As New Excel.Application
Dim sWindow As New WinWindow
ObjExcel.Visible = False
Dim stext As String
ObjExcel.Workbooks.Open("c:\data\calcresults.xlsx")
Dim ObjWS As Excel.Worksheet = ObjExcel.Worksheets("IP")
Dim iNextRow As Integer = ObjWS.UsedRange.End(Excel.XlDirection.xlDown).Row + 1
ObjWS.Cells(iNextRow,1 ) = "d66666"
ObjWS.Cells(iNextRow, 2) = "s77898"
would like use to Column Name not index, for example:
ObjWS.Cells(iNextRow,"Scenario" ) = "new row data, first column"
any ideas how can i do this?
I am guessing by your post that you are opening a workbook and updating the same column values each time?
What you could do is name the Range in Excel by selecting the cell in the sheet and entering the name into the Name Box as follows:
Then you can manipulate as follows:
Dim r1 As Range
Set r1 = ActiveSheet.Range("Scenario")
r1.Value = "OOps, changed it!"
r1.Offset(1, 0).Value = "This is A2"
Additionally you can just refer to the range:
Dim r As Range
Set r = ActiveSheet.Range("A1")
r.Value = "gello"
You can also set the name of a range for more than one cell - i.e. multiple rows/columns. Then manipulate with:
Dim r2 As Range
Set r2 = ActiveSheet.Range("SomethingElse")
r2.Cells(1) = "Summit Else 0"
r2.Cells(2) = "Summit Else 1"
r2.Cells(3) = "Summit Else 2"
I cannot see anything wrong with just accessing row/col index.