Remove duplicates excel vba [closed] - excel

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I tried to remove duplicates using below code. But I am not getting desired output. Along with duplicate data other data are also get removed.
Sub account()
Dim d As String
Call Pvt_Account(192, 8)
End Sub
Sub Pvt_Account(RowNumber As Integer,sheetnumber As Integer)
Worksheets(sheetnumber).Activate
NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count
m = RowNumber
CellNumber = 2
For i = 1 To NumRows - 1
Sheet2.Range("C" & RowNumber) = Application.WorksheetFunction.CountIf(Range("F2:F" & NumRows), Cells(CellNumber, 6))
Sheet2.Range("b" & RowNumber) = Worksheets(sheetnumber).Range("f" & CellNumber)
RowNumber = RowNumber + 1
CellNumber = CellNumber + 1
Next i
Worksheets(2).Activate
r = (m + NumRows) - 2
Range("B" & m & " :C " & r).RemoveDuplicates Columns:=Array(2), Header:=xlYes
End Sub

In
Range("B" & m & " :C " & r).RemoveDuplicates Columns:=Array(2), Header:=xlYes
, I think you will want Columns:=Array(1) instead, i.e. removing duplicates from the first column of the range Bm:Cr, which is B. The space after :C should also be removed.

Related

Copy a range of cells in a row and paste same row/range [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
Thats my data. I want to copy B2:M9 and insert it to P2. Furher, I want to copy B13:M20 and paste it to P2. Then I want to copy B24:M31 and paste it to P2 and so on.
Does anyone have an idea how I can do it?
Thank you!
Sub copypasta()
Dim nb_iter as Integer 'Number of ranges you have to copy
nb_iter = 3 'for example
Dim step as Integer
step = 0
for k = 1 to nb_iter
Range("B" & step + 2, "M" & step + 9).Copy
Range("P2").PasteSpecial , Paste:=xlPasteValues
step = step + 11 'you are adding 11 to both row numbers for each iteration
Next k
End Sub
My first attempt:
Sub Copypasta()
Dim i As Long
For i = 0 To 31
Range("B" & 2 + i, "M" & 9 + i).Copy
Range("P2").PasteSpecial Paste:=xlPasteValues
Next i
End Sub

Remove empty lines in txt export from [excel] [vba]

Not the best at VBA but I will give some context to help explain this probably stupid question.
The place I work for has a terrible system so we tend to do things our own way and use the system as little as possible.
We wanted to be able to take direct debits from customers as and when we need to and to do this we needed to create a 'BACS Standard 18' file to upload to the bank in order to collect the direct debits. The file requires there to be specific information about the transaction and it has to be displayed in a very specific way in notepad(txt).
I managed to create an Excel file that our finance team can use in order to create the file but when the file is created the typing cursor is always found to be a couple of lines under the exported text.
I need the text to be exported and the typing cursor to be at the end of the last line of the text, or a least not underneath. If it is under it, the bank will see that as a blank line and not accept the file. The number of lines in the file will always be different as well.
I have attached an example of the file in a screenshot. The highlighted part is what the file should include but as you can see the typing cursor is two lines lower.
Can someone please help with this and explain where I have gone wrong.
Thank you.
exportedfile
Below is the [vba] used to build the file and export the data from excel to notepad:
Sub Build_BACS()
LastRow = (Worksheets("Input").Range("Q2"))
'Header
ActiveSheet.Range("A1").Value = "=""VOL1""&Home!D5&"" ""&Home!D2&"" ""&""1"""
ActiveSheet.Range("A2").Value = "=""HDR1A""&Home!D2&""S""&"" ""&Home!D5&""00010001 ""&Home!D8&"" ""&Home!E8&"" 000000 """
ActiveSheet.Range("A3").Value = "=""HDR2F02000""&Home!B11&"" 00 """
ActiveSheet.Range("A4").Value = "=""UHL1 ""&Home!D8&""999999 000000001 DAILY 001 """
'Middle
ActiveSheet.Range("A5").Value = "=CONCAT(Input!C2,Input!D2,Input!K2,Input!G2,Input!H2,"" "",Input!L2,Input!M2,"" "",Input!N2,Input!O2)"
On Error Resume Next
Range("A5").AutoFill Destination:=Range("A5:A" & LastRow + 4), Type:=xlFillDefault
'Footer
If Sheets("Home").Range("A2").Value = "TMR" Or Sheets("Home").Range("A2").Value = "TMRF" Or Sheets("Home").Range("A2").Value = "TMREA" Then
Sheets("Output").Range("A" & LastRow + 5).Value = "=TEXT(Home!C2,""000000"")&TEXT(Home!B2,""00000000"")&""099""&TEXT(Home!C2,""000000"")&TEXT(Home!B2,""00000000"")&"" ""&TEXT(Input!P2,""00000000000"")&""The Mailing Room CONTRA TMR """
ElseIf Sheets("Home").Range("A2").Value = "DPS" Then
Sheets("Output").Range("A" & LastRow + 5).Value = "=TEXT(Home!C2,""000000"")&TEXT(Home!B2,""00000000"")&""099""&TEXT(Home!C2,""000000"")&TEXT(Home!B2,""00000000"")&"" ""&TEXT(Input!P2,""00000000000"")&""DPS CONTRA TMR """
End If
ActiveSheet.Range("A" & LastRow + 6).Value = "=""EOF1""&MID(A2,5,76)"
ActiveSheet.Range("A" & LastRow + 7).Value = "=""EOF2""&MID(A3,5,76)"
ActiveSheet.Range("A" & LastRow + 8).Value = "=""UTL1""&TEXT(Input!P2,""0000000000000"")&TEXT(Input!P2,""0000000000000"")&""0000001""&TEXT(Input!Q2,""0000000"")&"" """
'Export
Dim c As Range
Dim r As Range
Dim output As String
For Each r In Range("A1:A" & LastRow + 8).Rows
For Each c In r.Cells
output = output & c.Value
Next c
output = output & vbNewLine
Next r
Open ThisWorkbook.Path & "\" & ([Indirect("Home!B13")]) & ".txt" For Output As #1
Print #1, output
Close
InputBox "Noice." & Chr(13) & "Your file is just in here", "File Path", "Z:\My Documents\Orrin Lesiw\Direct Debit\Convert File"
End Sub
Adding ; to Print suppressed the vbNewLine. However output = output & vbNewLine will always add a newline so either add to front for lines 2 onwards like
Sub out2()
Dim c As Range
Dim r As Range
Dim output As String
For Each r In Range("A1:A" & LastRow + 8).Rows
If r.Row > 1 Then output = output & vbNewLine
For Each c In r.Cells
output = output & c.Value
Next c
Next r
Open ThisWorkbook.Path & "\" & ([Indirect("Home!B13")]) & ".txt" For Output As #1
Print #1, output;
Close
End Sub
or transpose the range into an array and use Join
' Export
Dim ar
ar = Application.Transpose(Range("A1:A" & LastRow + 8))
Open ThisWorkbook.Path & "\" & ([Indirect("Home!B13")]) & ".txt" For Output As #1
Print #1, Join(ar, vbNewLine);
Close

Can you explain how this line of code work (worksheet function)

Hello I'm new to vba and I have a project which at first seems quite simple but when I started to look at the range references I was totally lost. The Goal is to make a sum of multiple columns with one or two criterias.
For j = 9 To 12
For i = 3 To 6
datecol = 3
Cells(i, j).FormulaR1C1 = "=SUMIFS(R3C" & datecol & ":R" & Lastrow2 & "c" & datecol & ", R3C2:R" &
Lastrow2 & "C2, R" & i & "C8"
Next i
datecol = datecol + 1
Next j
End sub
What I have understand is that Cells(i,j) is where the output of my formula will be write.
.FormulaR1C1 return the formula as a string in the cell (i,j) -I think this is why we have ="=sumifs()-
Then we have SUMIFS(R3C" & datecol & ":R" & Lastrow2 & "c" & datecol & ") but what ":R", "c", & " mean ?
I know that this argument is the range use by the formula to make the sum but I don't understand the way ranges are referenced, and I have the same question for R3C2:R" "C2, R".
Help would be very appreciated, thank you.
Review and Suggestions
What do :R, c, & mean ?
In the context of R1C1 style R means row and C column. The & is a concatenation operator used to join the values ​​of two variables or constants. Very common used to create String variables.
For the macro you are trying to code you don't need to complicate yourself with .FormulaR1C1 use .Formula instead.
The line datecol = datecol + 1 is useless because datecol = 3 is inside the loop, so datecol will go back to 3 everytime the macro is looping. To solve this, datecol = 3 should be outside the loop.
When working with VBA is better to use functions that are meant to be runned in VBA and not in Excel, unless you wish to insert Excel formulas in cells. For instance the SUMIF function in VBA is: application.worksheetfunction.sumif(range,criteria,sum_range) Example of use: SumIfResult = Application.WorksheetFunction.SumIf(Range("A1:A10"), "In", Range("B1:B10"))
Descriptive Variables: use name or letters for your variables that describe them. It is easy to write software that works satisfactory. But it is very hard to write reliable, understandable and maintainable code. One important aspect is using good variable and function names. For instance, in the code below I changed the variables i and j for col and row_number.
I don't really get what you are trying to do, but I modified a little bit your code so you can maybe take some useful ideas.
Sub sum_columns()
'descriptive variable examples
Dim col As Long
Dim row_number As Long
Dim date_col As Long
Dim last_row2 As Long
date_col = 3
For col = 9 To 12
For row_number = 3 To 6
'this looks very complicated try to code it as simple as possible
'Cells(i, j).FormulaR1C1 = "=SUMIFS(R3C" & datecol & ":R" & Lastrow2 & "c" & datecol & ", R3C2:R" & Lastrow2 & "C2, R" & i & "C8"
'example
Cells(row_number, col).Formula = "=SUMIF(D" & row & ":D" & row + 3,">100)"
'another idea
Cells(row_number, col) = _
Application.WorksheetFunction.SumIf(Range("A1:A10"), "In", Range("B1:B10"))
Next row_number
date_col = date_col + 1
Next col
End Sub
Note
The code above is ONLY meant for explanation purposes (concepts, examples and ideas) NOT for executing it.

Find and replace values after looking up table

I have a sheet called "Table" where I have the table I'm looking up its A2:B20,
A2:A20 contains numbers in "XX" format these are the numbers I will be looking up.
The B2:B20 part of the table contains text is this text I want to use to replace values with.
I have my main sheet (currently called "Test") which contains my data, I want to look in Column M and check if I can find a value where the first 2 chars match any one of the values in A2:A20, if I do find a match I then want to replace the value of column F on my data sheet (Test) with the corresponding value from B2:B20 if not I want to leave it as is and move on.
I'm running into problems as the data in column M is numbers stored as text and it is replacing the wrong value when the table list 1 or 11 or 2 and 22.
'
Dim MyString As String
Counter = 2
1:
MyString = Sheets("Table").Range("A" & Counter).Value
For X = 1 To Range("M" & Rows.Count).End(xlUp).Row
If Replace(MyString, Left(Sheets("TEST").Range("M" & X).Value, 2), "") <> MyString Then Sheets("TEST").Range("F" & X).Value = Sheets("Table").Range("B" & Counter).Value
Next
Counter = Counter + 1
If Counter <= Range("M" & Rows.Count).End(xlUp).Row Then
GoTo 1:
Else
End If
End Sub
I solved my own problem, I was doing too much - simplified it forces values to .text and my issues went away.
Sub BBK_Name()
'Checks column U for start of data (1st 2 chars)
' if they match an entry in bank table changes entry in column G to match table entry.
'
Dim MyString As String
Counter = 2
1:
MyString = Sheets("Table").Range("A" & Counter).Text
RplcValue = Sheets("Table").Range("B" & Counter).Text
For X = 1 To Range("M" & Rows.Count).End(xlUp).Row
If Left(Sheets("TEST").Range("M" & X).Value, 2) = MyString Then _
Sheets("TEST").Range("F" & X).Value = RplcValue
Next
Counter = Counter + 1
If Counter <= Range("M" & Rows.Count).End(xlUp).Row Then
GoTo 1:
Else
End If
End Sub

Concatenate columns D and C using macro [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Could you please help in concatenating cells using Excel 2010 macro. I have columns A to E. I want to concatenate columns D and C in column F. Please note that I don't know the exact number of rows in column D and C but the macro should stop concatenating when there are no values in the said columns. Sample:
A B C D E F
0 Exist Echalas Gerald 25256 Gerald Echalas
....
Thank you.
Something like this (untested)
dim row as integer
row = 1
while(cells(row, 3) <> "" and cells(row, 4) <> ""
cells(row, 5) = cells(row, 3) & " " & and cells(row, 4)
row = row + 1
wend
Try this out, from MSDN, it has an example for going through each row.
http://support.microsoft.com/kb/213477
Their sample:
Sub ConcatColumns()
Do While ActiveCell <> "" 'Loops until the active cell is blank.
'The "&" must have a space on both sides or it will be
'treated as a variable type of long integer.
ActiveCell.Offset(0, 1).FormulaR1C1 = _
ActiveCell.Offset(0, -1) & " " & ActiveCell.Offset(0, 0)
ActiveCell.Offset(1, 0).Select
Loop
End Sub
This will combine values columns C, D to F as "D, C" regardless of gaps up to the last used row.
Sub CombineCols()
Dim oWS As Worksheet, lLastRow As Long, r As Long
Set oWS = ActiveSheet
lLastRow = oWS.Cells.SpecialCells(xlLastCell).Row
For r = 1 To lLastRow
' Combine if both C and D are not empty
If Len(oWS.Cells(r, 3)) > 0 And Len(oWS.Cells(r, 4)) > 0 Then
oWS.Cells(r, 6).Value = oWS.Cells(r, 4).Value & " " & oWS.Cells(r, 3).Value
End If
Next
End Sub
You can change the check condition so that it does not require both valid text is columns C and D to combine.
Tip: You can reference the column of a cell with long number - starting from A=1.
Lets say u r in sheet1
Sub test()
Dim r As Range
Dim lr As Integer
With Sheets("Sheet1")
lr = .Range("C500000").End(xlUp).Row
For Each r In .Range("F2:F" & lr)
r.Value = r.Offset(0, -2).Value & " " & r.Offset(0, -3).Value
Next r
End With
End Sub
Tested
Seems like a good job for a formula
Sub ConcatName()
With ActiveSheet
.Range("F1").Resize(.Range("A1").CurrentRegion.Rows.Count, 1).FormulaR1C1 = "=RC[-2]&"" ""&RC[-3]"
End With
End Sub
The CurrentRegion property gets the blob of data around A1, extends F1 by the number of rows, then inserts a formula that concatenates.
The concatenate function is quite easy to implement in a Macro. All you do is place an '&' between objects you would like to concatenate. In your case is would look like this:
Range("F1").Value = Range("C1").Value & " " & Range("D1")
*Note that I added a space between the C1 and D1 values
Next you are going to need a loop to iterate through your data. There are several good methods for controlling when the loop will stop.
Method #1
The simplest method is to not worry about when the macro stops. This may work in your case be concatenating nothing with nothing yields nothing.
loop
Range("F1").Value = Range("C1").Value & " " & Range("D1")
next
Method #2
End the loop when a specified column runs out of data. In your case this could look like:
While(Range("A" & i).value <> "")
Range("F1").Value = Range("C1").Value & " " & Range("D1")
i = i + 1
Wend
Method #3
Excel has a function (.count) that will return the number of entries in a column (will not work correctly if there are gaps). Use the value return along with a for loop to stop the loop when there is no more data.

Resources