Excel VBA constant arrays to vba code array - vba

I'm working on excel VBA school assignment and I have an issue and can't seem to find answer online.
I have database table that holds information, in certain location I have constant array of ={false, true, false} and I need it to convert it to VBA array TF(1 to 3)
TF(1) should have value of false
TF(2) should have value of true
TF(3) should have value of false
so far my code looks like this:
Sub trying()
Dim TF(1 To 3) As String
Set targetWorksheet = Worksheets("duomBazeSheet")
Worksheets("duomBazeSheet").Activate
With targetWorksheet
TF(1) = .Cells(2, 8).Value
MsgBox (TF(1))
End With
End Sub
"duomBazeSheet" is a sheet that has all data in it and target location is (2, 8)
any ideas?
edit: here's link how sheet looks : array is highlighted https://imgur.com/a/lII3c

Based on a feature called Evaluate one can do this
Dim tf
tf = Application.Evaluate("{True,False,True}")
Given the formula text in H2 try this ...
Sub Test()
Dim tf
tf = Application.Evaluate(ActiveSheet.Cells(2, 8).Formula)
Dim i
For i = LBound(tf) To UBound(tf)
MsgBox tf(i)
Next i
End Sub

The following code declares and populates a one-dimensional array with the values false, true, false. The For Loop will display each element at the end. It is unclear where you want to place these values.
Sub trying()
Dim TF As Variant
Dim i As Long
Dim targetWorksheet As Worksheet
Set targetWorksheet = Worksheets("duomBazeSheet")
With targetWorksheet
TF = Split(.Cells(2, 8).Value, Chr$(10)) 'Chr$(10) is a carriage return
End With
For i = LBound(TF) To UBound(TF)
MsgBox TF(i)
Next i
End Sub

Related

VBA Excel object required passing string array variable

I am attempting to pass an array of strings into a function as a variable and am getting a '424 Object required' error when I try to compare the values in the array to values in a given cell. I am new to VBA so this may be a simple syntax error but I cannot seem to figure it out. Here's my code:
Method being called:
Sub InitializeCharts()
'Set's up the array for checking data names in the social groups
Dim socialArray As Variant
socialArray = Array("Chores", "Meat & Potatos", "Work", "Wind Down", "Reward")
'...
Call ChartLogic(Range("'ActivityTracker'!B12"), Range("'Groups'!F4"), socialArray)
End Sub
ChartLogic Method:
Sub ChartLogic(dataCell As Range, tableCell As Range, socialArray As Variant)
Dim temp As Double
Dim count As Integer
'...
'Loops through the table and looks for the social cells with the same name, adding them to the chart
Do Until IsEmpty(dataCell)
For count = LBound(socialArray) To UBound(socialArray)
If socialArray(count).Value = dataCell.Value Then '<---Error Here
temp = socialCell.Offset(count, 0).Value
socialCell.Offset(count, 0).Value = temp + dataCell.Offset(0, 4).Value
End If
Next
Set dataCell = dataCell.Offset(1, 0)
Loop
End Sub
Thanks in advance!
You're getting an Object required error because socialArray(count) does not yield an object that has the property Value.
In other words, since socialArray is an Array of strings, socialArray(count) already yields a string—there's no need for Value.
As Andrew pointed out - socialArray(count).Value = will cause an error because it's a variant. You can store it as a local variable like this.
ArrVal = socialArray(count)
For count = LBound(socialArray) To UBound(socialArray)
ArrayVal = socialArray(count)
If ArrayVal = dataCell.Value Then '<---Error Here
temp = socialCell.Offset(count, 0).Value
socialCell.Offset(count, 0).Value = temp + dataCell.Offset(0, 4).Value
End If
Next
Or you could just take off the .value as it's not a cell and is not a worksheet object but a variant.
If socialArray(count) = dataCell.Value Then

Excel VBA - Dynamically supply ranges to Union method

User has defined named ranges to print in Excel.
I am reading these ranges into a VBA array. Is there a way to supply the range names to the Union method to set non-contiguous print ranges.
For example, something like:
ActiveSheet.PageSetup.PrintArea = Union(Range(array(1)), Range(array(2))).Address
The number of ranges held in the array can vary. I've experimented with looping through the array and building a string variable, but no success.
Any help would be appreciated.
You'll have to substitute the actual range names or objects in the statement, but here is how to use the Union function to set a PrintArea:
Sub foo()
Dim setup As PageSetup
Set setup = ActiveSheet.PageSetup
setup.PrintArea = Union(Range("MyRange1"), Range("MyRange2")).Address
End Sub
What I'm actually looking for is a method to construct the Union statement using range names that are held in an array
OK, then use the above method and a custom function to construct the Union in a loop:
Sub foo()
Dim setup As PageSetup
Dim RangeArray(1) As Range
Set setup = ActiveSheet.PageSetup
Set RangeArray(0) = Range("MyRange1")
Set RangeArray(1) = Range("MyRange2")
setup.PrintArea = GetUnion(RangeArray)
End Sub
Function GetUnion(arr As Variant) As String
Dim itm As Variant
Dim ret As Range
For Each itm In arr
If Not ret Is Nothing Then
Set ret = Union(ret, itm)
Else
Set ret = itm
End If
Next
If Not ret Is Nothing Then
GetUnion = ret.Address
Else
GetUnion = "" 'May cause an error...
End If
End Function

Excel VBA using Combobox with Index Match

I have an Excel VBA UserForm Combobox for scanning asset tags to compare against a site baseline held in Sheet1. There can be upto 50,000+ assets. The named ranges are all correct.
I want the loop to fill the "Found" Asset attribute Textboxes for Type, Serial, MakeModel, Location & PrinterHost.
The code is below without the additional index match lookups for extra asset attributes as the process will be the same. Help appreciated as I'm not sure where I'm going wrong. Thanks in advance.
Private Sub ComboScanTag_Change()
Dim x As Integer
Dim AssetCount As Long
Dim BASELINE As Range
Dim AssetID As Range
Dim FoundType As Variant
Dim FoundSerial As Variant
Dim FoundMakeModel As Variant
Dim FoundLocation As Variant
Dim FoundPrinterHostName As Variant
If Me.ComboScanTag.Value = "" Then 'ScanTag has no value
MsgBox "Asset not Found - Re-Scan or enter New Asset details"
Me.ComboScanTag.SetFocus
End If
If Me.ComboScanTag.Value <> "" Then 'ScanTag has a value
Application.ScreenUpdating = False 'Turn off screen updating to speed app
For x = 1 To AssetCount 'Number of loop iterations from Baseline Assets Count D1 cell
FoundType = Application.Index("BASELINE", Application.Match(Me.ComboScanTag.Value, "AssetID", False), 3)
If Not IsError(FoundType) = False Then 'if error value in lookup return 0
Me.txtFoundType.Value = FoundType 'Fill textbox FoundType with lookup value from baseline
Else
On Error GoTo 0 'reset error handler
FoundSerial = Application.Index("BASELINE", Application.Match(Me.ComboScanTag.Value, "AssetID", False), 11)
If Not IsError(FoundSerial) = False Then
Me.txtFoundSerial.Value = FoundSerial
End If
Next x
End If
Application.ScreenUpdating = True
End Sub
AssetCount is not initialized. You need to initialize it before you use it like AssetCount = 10.
BASELINE and AssetID are not set as well.
If BASELINE and AssetID are named ranges, you cannot use it the way you do in Application.Index or Application.Match.
You need to pass it as object and not as string like this:
Set BASELINE = ThisWorkbook.Names("BASELINE").RefersToRange
Set AssetID = ThisWorkbook.Names("AssetID").RefersToRange
Then you can use it like this in Application.Index and Match:
With Application
FoundType = .Index(BASELINE, .Match(Me.ComboScanTag.Value, AssetID, False), 3)
End With

Convert VBA Macro to Function

I have been trying to create a function to retrieve column titles found in row four in an excel sheet. This is what I have so far, can anybody help me please?
Sub Test_Click()
Dim text As String
Dim titles(200) As String
Dim nTitles As Integer
For i = 1 To 199
If Trim(Sheets("Sheet1").Cells(4, i).Value) = "" Then
nTitles = i - 1
Exit For
End If
titles(i - 1) = Sheets("Sheet1").Cells(4, i).Value
Next
For i = 0 To nTitles
Sheets("Sheet1").Cells(20 + i, 1).Value = titles(i)
Next
End Sub
You need to make an array function for this. So your function will take in inputs through a range
Function ReturnArray(Input as Range) as Variant
' Do stuff with the Input range
Dim Output(m,n) as Variant
'Loop through m,n to fill in the output values as you would in a range
ReturnArray = Output
End Function
And when you put in the function in excel, type it in the cell after highlighting where you want the output and press Ctrl-Shift-Return
Just as you write a Sub you can write a Function, just substitute the words at the beginning and at the end of your code.
Now, about how to return the values, obviously it will be an array, so you'll need to declare the array, set its size, fill its cells and return it. This can be done like this:
Function yourFunction() as String()
' You already have an array named "titles" which stores the values you want
' to return. Fill it exactly as you do in your original code.
yourFunction = titles ' This is the way to return the array.
End Function
If you want to use this function in a worksheet (as a formula), remember that this is an array-function, so you'll need to press Ctrl+Shitf+Enter after you enter the function in the cell instead of just [Enter].

VBA code to hide a number of fixed discrete rows across a few worksheets

I'm for a solution to part of a macro I'm writing that will hide certain (fixed position) rows across a few different sheets. I currently have:
Sheets(Sheet1).Range("5:20").EntireRow.Hidden = True
To hide rows 5-20 in Sheet1. I also would like to hide (for arguements sake), row 6, row 21, and rows 35-38 in Sheet2 - I could do this by repeating the above line of code 3 more times; but am sure there's a better way of doing this, just as a learning exercise.
Any help much appreciated :)
Chris
Specify a Union of some ranges as follows
With Sheet1
Union(.Range("1:5"), .Rows(7), .Range("A10"), .Cells(12, 1)).EntireRow.Hidden = True
End With
Here is a try:
Sub hideMultiple()
Dim r As Range
Set r = Union(Range("A1"), Range("A3"))
r.EntireRow.Hidden = True
End Sub
But you cannot Union range from several worksheets, so you would have to loop over each worksheet argument.
This is a crude solution: no validation, no unhiding of existing hidden rows, no check that I have a sheet name as first parameter, etc. But it demonstrates a technique that I often find useful.
I load an array with a string of parameters relevant to my current problem and code a simple loop to implement them. Look up the sub and function declarations and read the section on ParamArrays for a variation on this approach.
Option Explicit
Sub HideColumns()
Dim InxPL As Integer
Dim ParamCrnt As String
Dim ParamList() As Variant
Dim SheetNameCrnt As String
ParamList = Array("Sheet1", 1, "5:6", "Sheet2", 9, "27:35")
SheetNameCrnt = ""
For InxPL = LBound(ParamList) To UBound(ParamList)
ParamCrnt = ParamList(InxPL)
If InStr(ParamCrnt, ":") <> 0 Then
' Row range
Sheets(SheetNameCrnt).Range(ParamCrnt).EntireRow.Hidden = True
ElseIf IsNumeric(ParamCrnt) Then
' Single Row
Sheets(SheetNameCrnt).Range(ParamCrnt & ":" & _
ParamCrnt).EntireRow.Hidden = True
Else
' Assume Sheet name
SheetNameCrnt = ParamCrnt
End If
Next
End Sub