Vba how to compare 2 column - string

I'm making an heuristic analyse and i have the fallowing problem : I want to find in column D numbers that match with column J and replace them by a "0". You can see what I'm trying to do on this image :
Problem : Column D have multiples values per cell and column J have one value per cell.
some part of the code:
Dim i,j As Integer
Dim temp As String
Dim x As Integer
Dim d As String
i = Application.CountA(Range("E:E")) + 10
'number of cell with values
j = Application.CountA(Range("J:J")) + 10
For j = 11 To j
temp = Range("J" & j).Value
For i = 11 To i
d = Range("D" & i).Value
*For x = LBound(vec) To UBound(vec)
If vec(x) = temp Then
vec(x) = 0
Range("D" & i).Value = vec(x)
End If
Next
Next
Next
*-> Here it is the problem, i cant figured out how to pass over the coma "," in column D,and store the data. I want to compare the temp with value on "d", but "d" can i have multiple numbers on the same cell, like " 3, 2, 1", and if there is any match like temp = 3, then d= "0,2,1".
English is not my native language so i hope you can understand what i want.
Thanks!

I think your almost there you just need to split up each cell and then search then recreate and replace the string in the cell. Please note I've not tested this.
Dim i,j As Integer
Dim temp As String
Dim x As Integer
Dim d As String
i = Application.CountA(Range("E:E")) + 10
'number of cell with values
j = Application.CountA(Range("J:J")) + 10
For j = 11 To j
temp = Range("J" & j).Value
For i = 11 To i
d = Range("D" & i).Value
Vec = split(d, ",") 'split the cell
d = "" 'clear the string
For x = LBound(vec) To UBound(vec)
If vec(x) = temp Then
vec(x) = 0
End If
d = d & vec(x) & "," 'recreate the string
Next
Range("D" & i).Value = left(d, len(d) - 1) 'save the string without the last ,
Next
Next

you can do this with the below formula - no need for VBA
Make a new column somewhere near column D.
In your new column, use this FIND and Substitute formula:
=IF(NOT(ISERROR(FIND(J:J,D:D))),SUBSTITUTE(D:D,J:J,"0"),D:D)
This formula looks for the value in column J within the cells in column D.
If a match is found, 0 is substituted for the found number. Otherwise, column D is returned.
If you want, you can hide column D to avoid confusion.
in VBA you have a string function called Split(vString, delimiter) that will split a string into tokens using the specified delimiter. See
MSDN Library: VB Split Function
examples:
Mr Spreadsheet John Walkenbach: Split Function examples
VB-Helper

Related

Excel: Combine multiple (16) columns of data to form unique combinations

First time here, thank you all in advance!
I have minimal VBA experience but believe the solution likely requires it.
The question:
I have 16 columns of data, each 8 rows long:
Columns A,C,E,G,I,K,M,O: 1,2,3,4,5,6,7,8
Columns B,D,F,H,J,L,N,P: A,B,C,D,E,F,G,H
My goal is to make a column of strings with one value from each of the 16 columns without duplicating a number or letter. The string would maintain a number-letter-number-letter- etc order.
For example:
Accepted results would be: A1B2C3D4E5F6G7H8, A1B2C3D4E5F6G8H7
Duplicate letters or numbers would NOT be included: A1B2C3D4E5F6G7A8, A1B1C3D4E5F6G7H8
Is this something that is programmable via VBA? Many thanks in advance!
In rows varable you specify how many rows you have and in variable cols you specify how many columns you have (since you told that you have 16 columns, I advise you to leave it as it is).
Sub t()
Dim rows As Integer, cols As Integer
Dim str, strToAppend As String: str = ""
rows = 1
cols = 16
For i = 1 To rows
For j = 2 To cols Step 2
strToAppend = Cells(i, j).Value
If InStr(str, strToAppend) = 0 Then
str = str & strToAppend
End If
strToAppend = Cells(i, j - 1).Value
If InStr(str, strToAppend) = 0 Then
str = str & strToAppend
End If
Next j
Cells(i, cols + 1).Value = str
str = ""
Next i
End Sub

Vlookup, return multiple values to a cell

is there anyway to return multiple values from a vlookup? I would like col I in Sheet 1 to return multiple values to a cell, or is there another way of displaying this (would rather not pivot)?
Sheet 1 : has all my unique values (Col F, and returning values in Col I),
Sheet 3: Col A has duplicate string values which correspond to unique strings in Col B which are unique, including blanks.
EDIT
Sheet 1 or desired result :
Sheet 1: Current
Sheet 3 Current:
Current formula
=VLOOKUP(F2,Sheet3!A:B,2,FALSE)
Returns mostly 0's, due to the blanks or multiple values corresponding to the unique values.
In terms of VBA then, you have to change the code a bit from what was in the link I sent you. This should work:
Option Explicit
Function vlookupmulti(rngLookup As Variant, rngSource As Range, col As Double) As String
Dim d As Double, strCell As String
'Error if range has less columns than col
If rngSource.Columns.Count < col Then
vlookupmulti = CVErr(xlErrNA)
Exit Function
End If
'Loop through rows in the lookup column
For d = rngSource.Row To rngSource.Rows.Count
If rngLookup = Sheets(rngSource.Parent.Name).Cells(d, rngSource.Column).Value Then
strCell = Sheets(rngSource.Parent.Name).Cells(d, rngSource.Column + col - 1).Value
If Len(strCell) > 0 Then vlookupmulti = vlookupmulti & strCell & ", "
End If
Next d
'Remove comma at end
If Right(vlookupmulti, 2) = ", " Then
vlookupmulti = Left(vlookupmulti, Len(vlookupmulti) - 2)
End If
'Give error if no results
If vlookupmulti = "" Then
vlookupmulti = CVErr(xlErrNA)
End If
End Function

Multiple array assignment to an excel range

Just out of curiosity ,I am asking you a question which is as below:
Suppose i do have an array A1(6)=(45,25,,36,88),A2(6)=(14,25,11),A3(6)=(11,21,20,25,48).Now can we put those array values with the help of a single statement like single array assignment to a row,as here all the rows to a range of an Excel, Say here "C1:R3" range.
EDIT
If I need to assign them to a row like R1<- A1 + A2 +A3,R2<- A1 + A2 +A3. Can you tell me how to this?
R1<- (45,25,,36,88),14,25,11,,,,11,21,20,25,48,) same for R2.
Thanks,
Dim A(2,5)
For i = 0 to 5
A(0, i) = A1(i)
A(1, i) = A2(i)
A(2, i) = A3(i)
Next i
Range("C1:R3").Value = A
EDIT
For second part, to the best of my understanding:
Dim R(17)
For i = 0 To 2
For j = 0 To 5
R(6 * i + j) = A(i, j)
Next j
Next i
Range("C5:T5").Value = R
EDIT 2
Alternatively:
Dim R
R = Split(Join(A1, ",") & "," & Join(A2, ",") & "," & Join(A3, ","), ",")
Range("C5:T5").Value = R
You can use any delimiter you like (if it's appropriate for your data).

Check if any rows are duplicate and highlight

I have data in (Sheet4) columns A to I:
I'm trying to compare data for all rows (Only on column A and B) to see if any of the rows is duplicated, if it is: excel should highlight both rows.
Example:
A B C......I
s 1 x
s 3 w
e 5 q
s 1 o
Row 1 and 4 should be highlighted as values are the same for column A and B.
I shouldn't modify the sheet (no modification to the columns or rows should be done to the sheet), and the number of rows is not always known (not the same for all files).
Is there an easy way (using macros) to do this???
This is an attempt I have tried, but it is increasing my file to 7MB!!!!! I'm sure there should be an easier way to compare rows for an unknown number of rows and just highlight the dupllicates if they exist:
Public Sub duplicate()
Dim errorsCount As Integer
Dim lastrow As Integer
Dim lastrow10 As Integer
errorsCount = 0
lastrow = Sheet4.Cells(Rows.Count, "A").End(xlUp).Row 'is the row number of the last non-blank cell in the specified column
lastrow10 = lastrow
Sheet10.Range("B1:B" & lastrow10).Value = Sheet4.Range("A1:A" & lastrow).Value
Set compareRange = Sheet10.Range(column + "2:" & Sheet10.Range(column + "2").End(xlDown).Address)
For Each a In Sheet10.Range(column + "2:" & Sheet10.Range(column + "2").End(xlDown).Address)
c = a.Value
If c <> Null Or c <> "" Then
If name = "testing" Then
If WorksheetFunction.CountIf(compareRange, c) > 1 Then
a.Interior.ColorIndex = 3
errorsCount = errorsCount + 1
End If
End If
End If
Next a
If errorsCount > 0 Then
MsgBox "Found " + CStr(errorsCount) + " errors"
Else
MsgBox " No errors found."
End If
End Sub
Silly answer to you.
J1 or just duplicate sheet.
J1 =CONCATENATE(A1,"#",B1) > drag down > J:J > conditional format > highlight cells rules > duplicate values.
(* replace the # to any string which you think not possible in the original A:A and B:B.)
I do this all the time.
To collect all duplicates just SORT with color.

VBA Finding the next column based on an input value

In a program that I'm trying to write now I take two columns of numbers and perform calculations on them. I don't know where these two columns are located until the user tells me (they input the column value in a cell in the workbook that my code is located in).
For example, if the user inputted "A" and "B" as the columns where all the information is in I can perform calculations based on those values. Likewise if they wanted to analyze another worksheet (or workbook) and the columns are in "F" and "G" they could input those. The problem is that I'm asking the user to input those two columns as well as four others (the last four are the result columns). I did this in hopes that I would be able to make this flexible, but now inflexibility is acceptable.
My question is, if I'm given a value of where some information will be (let's say "F") how can I figure out what the column will be after or before that inputted value. So if I'm only given "F" I'll be able to create a variable to hold the "G" column.
Below are examples of how the variables worked before I needed to do this new problem:
Dim first_Column As String
Dim second_Column As String
Dim third_Column As String
first_Column = Range("B2").Text
second_Column = Range("B3").Text
third_Column = Range("B4").Text
Here the cells B2 - B4 are where the user inputs the values. Generally I want to be able to not have the B3 and B4 anymore. I feel like the Offset(0,1) might be able to help somehow but so far I've been unable to implement it correctly.
Thank you,
Jesse Smothermon
Here are two functions that will help you dealing with columns > "Z". They convert the textual form of a column to a column index (as a Long value) and vice versa:
Function ColTextToInt(ByVal col As String) As Long
Dim c1 As String, c2 As String
col = UCase(col) 'Make sure we are dealing with "A", not with "a"
If Len(col) = 1 Then 'if "A" to "Z" is given, there is just one letter to decode
ColTextToInt = Asc(col) - Asc("A") + 1
ElseIf Len(col) = 2 Then
c1 = Left(col, 1) ' two letter columns: split to left and right letter
c2 = Right(col, 1)
' calculate the column indexes from both letters
ColTextToInt = (Asc(c1) - Asc("A") + 1) * 26 + (Asc(c2) - Asc("A") + 1)
Else
ColTextToInt = 0
End If
End Function
Function ColIntToText(ByVal col As Long) As String
Dim i1 As Long, i2 As Long
i1 = (col - 1) \ 26 ' col - 1 =i1*26+i2 : this calculates i1 and i2 from col
i2 = (col - 1) Mod 26
ColIntToText = Chr(Asc("A") + i2) ' if i1 is 0, this is the column from "A" to "Z"
If i1 > 0 Then 'in this case, i1 represents the first letter of the two-letter columns
ColIntToText = Chr(Asc("A") + i1 - 1) & ColIntToText ' add the first letter to the result
End If
End Function
Now your problem can be solved easily, for example
newColumn = ColIntToText(ColTextToInt(oldColumn)+1)
EDITED accordingly to the remark of mwolfe02:
Of course, if you are not interested in the column names, but just want to get a range object of a specific cell in a given row right beneath a column given by the user, this code is "overkill". In this case, a simple
Dim r as Range
Dim row as long, oldColumn as String
' ... init row and oldColumn here ...
Set r = mysheet.Range(oldColumn & row).Offset(0,1)
' now use r to manipulate the cell right to the original cell
will do it.
You were on the right track with Offset. Here is a test function that shows a couple different approaches to take with it:
Sub test()
Dim first_Column As String
Dim second_Column As String
Dim third_Column As String
Dim r As Range
first_Column = Range("B2").Text
second_Column = Range("B2").Offset(1, 0).Text
third_Column = Range("B2").Offset(2, 0).Text
Debug.Print first_Column, second_Column, third_Column
Set r = Range("B2")
first_Column = r.Text
Set r = r.Offset(1, 0)
second_Column = r.Text
Set r = r.Offset(1, 0)
third_Column = r.Text
Debug.Print first_Column, second_Column, third_Column
End Sub
UPDATE: After re-reading your question I realize you were trying to do offsets based on a user-entered column letter. #rskar's answer will shift the column letter, but it will be a lot easier to work with the column number in code. For example:
Sub test()
Dim first_Col As Integer, second_Col As Integer
first_Col = Cells(, Range("B2").Text).Column
second_Col = first_Col + 1
Cells.Columns(first_Col).Font.Bold = True
Cells.Columns(second_Col).Font.Italic = True
End Sub
There are a few syntactical problems with #rskar's answer. However, it was helpful in producing a function that grabs a column "letter", based on an input column "letter" and a desired offset to the right:
Public Function GetNextCol(TheCol As String, OffsetRight As Integer) As String
Dim TempCol1 As String
Dim TempCol2 As String
TempCol1 = Range(TheCol & "1").Address
TempCol2 = Range(TempCol1).Offset(0, OffsetRight).Address(0, 0, xlA1)
GetNextCol = Left(TempCol2, Len(TempCol2) - 1)
End Function
In light of the comments of others (and they all raised valid points), here is a much better solution to the problem, using Offset and Address:
Dim first_Column As String
Dim second_Column As String
Dim p As Integer
first_Column = Range("B2").Text
second_Column = _
Range(first_Column + ":" + first_Column).Offset(0, 1).Address(0, 0, xlA1)
p = InStr(second_Column, ":")
second_Column = Left(second_Column, p - 1)
The above should work for any valid column name, "Z" and "AA" etc. included.
Make use of the Asc() and Chr() functions in VBA, like so:
Dim first_Column As String
Dim second_Column As String
first_Column = Range("B2").Text
second_Column = Chr(Asc(first_Column) + 1)
The Asc(s) function returns the ASCII code (in integer, usually between 0 and 255) of the first character of a string "s".
The Chr(c) function returns a string containing the character which corresponds to the given code "c".
Upper case letters (A thru Z) are ASCII codes 65 thru 90. Just google ASCII for more detail.
NOTE: The above code will be fine so long as the first_Column is between "A" and "Y"; for columns "AA" etc., it will take a little more work, but Asc() and Chr() will still be the ticket to coding for that.

Resources