Delete duplicates within an array in vba Excel - arrays

I've got values inside an array and I would like to delete the values with are double entries, e.g. I have EUR,EUR,EUR,GBP,YEN and I like to remove the double euro entries within removing them from the execel spreadsheet.
Just save then in an array. The new array should look like that: EUR,GBP,YEN
After that I would like to write them to another spreadsheet.
My code so far:
Dim ArrayCurrency As Variant
RangeStart = "E2"
RangeEnd = "E"
RangeNew = RangeStart & ":" & RangeEnd & lRow
CurrencyArray = Range(RangeNew).Value
For Each element In CurrencyArray
Next element
I hope that you can help me!
Best regards
Matthias

Use Dictionary object for unique values - in the future.
For your current case, you may use RemoveDuplicates method on the range.

Related

VBA to assign a cell as an array formula

I have a sheet called "Total" that I have to duplicate which contains an array formula. When I create a copy and rename it, the array formula is no longer entered as an array.
when I record a macro its looks like the following.
Range("B55").Select
Selection.FormulaArray = _
"=IF(R1C1=""Total"",INDEX('[All_File.xlsm]Sheet1'!R4C5:R8C5,MATCH(R[-53]C,'[All_File.xlsm]Sheet1'!R4C2:R8C2,0)),INDEX('[All_File.xlsm]Sheet1'!R5,MATCH(R1C1&""Groups"",'[All_File.xlsm]Sheet1'!R4&'[All_File.xlsm]Sheet1'!R3,0)))"
This issue with this is that it is referencing the file in the formula. The file reference can change so this recorded macro would not work.
Is there a way to select a cell and have it be entered as an array?
For example:
Range("B55").Select
Selection.FormulaArray
the cell is being selected and entered as an array. Again my issue with the recorded macro is that it is storing the file name, which will change, so the recorded macro cant be used again.
You can replace the file name before adding the formula:
Dim f As String, myFile
f = "=IF(R1C1=""Total"",INDEX('[{file}]Sheet1'!R4C5:R8C5,MATCH(R[-53]C," & _
"'[{file}]Sheet1'!R4C2:R8C2,0)),INDEX('[{file}]Sheet1'!R5," & _
"MATCH(R1C1&""Groups"",'[{file}]Sheet1'!R4&'[{file}]Sheet1'!R3,0)))"
myFile = 'get your filename here...
Range("B55").FormulaArray = Replace(f, "{file}", theFilename)

How to insert values from a one dimensional array given by ETABS into a range in excel using VBA

I am trying to insert values from a one dimensional array given to me by a program (ETABS) into a range in Excel using VBA.
This is how the results are returned to you by the ETABS program (please read to understand): http://docs.csiamerica.com/help-files/common-api(from-sap-and-csibridge)/SAP2000_API_Fuctions/Analysis_Results/Results/Analysis_Results_Remarks.htm
Therefore in order for me to insert ONE result into cell "A1" in Excel I just use this code (WHICH WORKS):
Range("A1").Value = U1(0)
But if I want to insert ALL of the results into a certain Range I am running into all types of problems..I've tried many codes, but this one seemed to be the most reasonable:
Range("A1:A" & (NumberResults - 1)).Value = (U1(0) - U1(NumberResults - 1))
I usually get only the first value repeated all throughout the range instead of the whole set of values.
Does anybody have an idea of how to make all of the values of the array appear in the designated range?
Thanks!
Because the arrayU1() is zero-based:
Dim i As Long
For i = LBound(U1) To UBound(U1)
Range("A" & i + 1).Value = U1(i)
Next i

VBA Associative Arrays (How to Index)

I'm a newbie to VBA so please forgive my lack of experience.
Im using excel VBA and trying to figure out how to index an array. I'm importing a CSV and using the split function. I need to access each individual items of the items split into the array(s). The best way to explain what I need is an example like this from Actionscript:
var a:Array = [];
a[1] = "Hello";
a[2] = "World";
(Except that what I have is a dynamic array created by the SPLIT function)
Where I could access "Hello" with the var a[1]
Here is what I have so far:
Sub getTxtfile()
FilePath = Application.GetOpenFilename _
(Title:="Please choose a file to open", _
FileFilter:="CSV Files *.csv* (*.csv*),")
Open FilePath For Input As #1
row_number = 0
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, ",")
'ActiveCell.Offset(row_number, 0).Value = LineItems(1)
'ActiveCell.Offset(row_number, 1).Value = LineItems(0)
row_number = row_number + 1
'Debug.Print LineItems(0) & ": " & LineItems(1)
Loop
Close #1
End Sub
I now have 2 arrays (LineItems(0) & LineItems(1)) but how do I index what is inside of them at this point?
Thanks for any and all help, it is greatly appreciated.
Mike
The CSV I'm using is formatted to use with other applications SolidWorks, python, etc.) besides Excel. I need to access only certain elements within the array to populate certain cells. As it is...I can pull the entire array into columns but I don't want to do that, just the ones I need. Here is a sample of the CSV:
0,.200
p,1.0709
q,1.167
r,1.177
s,1.216
t,1.570
u,1.5843
v,1.6883
w,1.9079
e,.2645
What I want to do is reference the letter in the first element and have the second element inserted in a certain cell: Reference "t" through an index and have "1.570" inserted.
The elements in my arrays are LineItems(0) and LineItems(1). So ideally I'm looking to reference each indexed item in an element as LineItems(1)(a) / LineItems(1-a) or something similar to that.
I think the commented-out lines in your code should actually work, at least as far as array access is concerned. (However, I may not fully understand what you are trying to accomplish. Would you please edit your question to clarify?) I do recommend adding
Option Explicit
Option Base 0
at the top of your file, and
Dim LineItems as Variant
before the Split call. That way the compiler will help you find errors.
However, If what you really want is to open a CSV, please allow me to suggest:
Dim wb as Workbook
Workbooks.OpenText Filename:="<filename>", DataType:=xlDelimited, Comma:=True
Set wb = Workbooks(Workbooks.Count)
which will give you a new workbook wb with the CSV parsed and ready to be accessed just like any other worksheet (docs on MSDN).
You can have associative arrays in VBA with Scripting.Dictionary object or the .NET System.Collections.HashTable, but that seems a bit overkill.
You can use Jagged Arrays (Arrays of Arrays) like this:
Line = "0,.200 p,1.0709 q,1.167 r,1.177 s,1.216 t,1.570 u,1.5843 v,1.6883 w,1.9079 e,.2645"
LineItems = Split(Line, ",")
Dim LineSubItems() ' has to be Variant or Variant() array
ReDim LineSubItems(0 To UBound(LineItems))
For i = 0 To UBound(LineItems)
LineSubItems(i) = Split(LineItems(i), " ")
Next
Debug.Print LineSubItems(1)(1) ' "p"

remove duplicate rows in array

I have a question about arrays. First let me show you the code that I have got:
Dim TopStud() As Variant
TopStud = Range("A1", Range("A2").End(xlDown).End(xlToRight))
'code that removes duplicate values in array
'end code
Worksheets.Add
Range(ActiveCell, ActiveCell.Offset(UBound(TopStud, 1) - 1, UBound(TopStud, 2) - 1)).Value = TopStud
The code above shows how I get a range of values in an array. I want to remove duplicate values that is been saved in this array into a new worksheet. See above. Is there a easy way to do this?
I want the following result:
If you want to remove the whole record for any duplicates in the current column:
Cells.RemoveDuplicates Columns:=ActiveCell.Column,Header:=xlYes

VBA AutoFilter multiple worksheets based on array of numbers, ignore if not in list

Let's say I have a workbook with 3 worksheets on it. I've filtered down the first sheet based on column State that equals Ohio. I then get a list of values from that filtered list from column ID and put them into an Integer/Long array. Basically I put all the ID's for each row that has the state column Ohio.
I am now trying to filter the remaining tables based on their ID column where they match my array of ID's. The problem is when it comes across filtered ID's that are not in the new sheet, instead of providing me with the matches for each sheet, I am left with only the last matching value. Here's an example of my VBA trying to filter the remaining sheets:
For Each sheet In Worksheets
If sheet.Name <> "Sheet1" Then
sheet.Activate
columnNum = ActiveSheet.UsedRange.Find("ID").Column
ActiveSheet.AutoFilterMode = False
ActiveSheet.UsedRange.AutoFilter
'***Problem is here
ActiveSheet.UsedRange.AutoFilter Field:=columnNum, Criteria1:=mainIDs, Operator:=xlFilterValues
End If
Next
As I mentioned earlier mainIDs is an array of Integer that is being carried over to each sheet to filter on. Why is it only bringing me back the last match? Do I need to somehow tell it to ignore filtered values that aren't in the new sheet? How?
EDIT: Here's how I filled my array
Dim mainIDs() As Long, size As Integer, i As Integer
size = ActiveSheet.UsedRange.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 2
ReDim mainIDs(size)
i = 0
For Each row In .UsedRange.Columns(1).SpecialCells(xlCellTypeVisible)
If row.Value <> "ID" Then '***Column header
mainIDs(i) = row.Value
i = i + 1
End If
Next
If you use an array for filtering you have to cast the values to strings before.
As I understood you're adding integer/long values to the array. Autofilter can't work with this.
In addition you have to change your array to a string array mainIDs() as String or declare it as Variant.
For Each row In .UsedRange.Columns(1).SpecialCells(xlCellTypeVisible)
If row.Value <> "ID" Then '***Column header
mainIDs(i) = Cstr(row.Value) 'Cast values to string
i = i + 1
End If
Next
Then it should work, please let me know if it helped you.
If you use arrays as Criteria, you'll have to use a 1D array.
But then, you need to supply the Operator argument to actually filter all that is in the array.
Sample:
ActiveSheet.UsedRange.AutoFilter Field:=columnNum, _
Criteria1:=mainIDs, _
Operator:xlFilterValues
To know more about AutoFilter Method check MSDN.

Resources