Why won't the concatenate function in vba work? - excel

I am new to vba and need a little help. I want to copy copy column A & C to sheet 2 but my concatenation syntax (my_range = rng1&":"&rng2) won't work.
I have tried other syntax too but it's just syntax to concatenate Strings into a single column and that's what I am looking for. What I want is Column A & C from sheet 1 to be copied in Column A & B in sheet 2.
Sub CommandButton1_Click()
Dim my_range As String, rng1 As String, rng2 As String
search_value = Sheets(2).Cells(i, 1).Value = 1
Sheets(1).Activate
For i = 2 To 100
If Sheets(1).Cells(i, 1).Value = search_value Then
rng1 = "A" & i
rng2 = "C" & i
my_range = rng1&":"&rng2
Sheets(1).Rande(my_range).Select
Selection.Copy
Sheets(2).Activate
Sheets(2).Range("A2").Select
Selection.PasteSpecial: xlPasteAll , SkipBlanks:=True, Transpose:=False
End If
Next
Application.CutCopyMode = False
Sheets(2).Cells(1, 2).Select
End Sub

The simplest way to create a range from one cell to the other is the following:
my_range = Range(rng1, rng2)
(I found some examples on this website.)

Do it like below :
rng1 = "A" & CStr(i)
rng2 = "C" & CStr(i)
my_range = rng1 & ":" & rng2

Related

Why is my macro starting in row 1 instead of row 2?

I'm not sure why my macro is starting this =TRIM(F2) formula in cell E1 instead of E2.
'Insert TRIM Contract Column & formula
Set rngHeaders = Range("1:1") 'Looks in entire first row
Set rngUsernameHeader = rngHeaders.Find(what:="Contract", After:=Cells(1, 1))
rngUsernameHeader.EntireColumn.Insert
Range("E1").Value = "TRIM CONTRACT"
Range("E1").Font.Bold = True
Range("E2").Select
Dim lastRow As Long
lastRow = Range("E2:E" & Rows.Count).End(xlUp).Row
Range("E2:E" & lastRow) = _
"=TRIM(F2)"
Range("E2:E" & lastRow).Select
Range("E2:E" & Range("F" & Rows.Count).End(xlUp).Row).FillDown
I'm just trying to insert a column (column E) that contains the TRIM values in the column next to it (column F, aka 'Contract')
This should work, I also removed all unnecessary lines:
Option Explicit
Sub Macro3()
'Insert TRIM Contract Column & formula
Set rngHeaders = Range("1:1") 'Looks in entire first row
Set rngUsernameHeader = rngHeaders.Find(what:="Contract", After:=Cells(1, 1))
rngUsernameHeader.EntireColumn.Insert
Range("E1").Value = "TRIM CONTRACT"
Range("E1").Font.Bold = True
Dim lastRow As Long
lastRow = Range("F" & Rows.Count).End(xlUp).Row
Range("E2:E" & lastRow) = "=TRIM(F2)"
End Sub
Cheers .
Followup:
If you don't know what column is going to contain "Contract" you need to make all further cell references related to your found cell:
Option Explicit
Sub Insert_Formula_Found_Column()
'Insert TRIM Contract Column & formula
Dim RngHeaders As Range
Dim RngUserNameHeader As Range
Dim BuiltFormula As String
Set RngHeaders = Range("1:1") 'Looks in entire first row
Set RngUserNameHeader = RngHeaders.Find(what:="Contract", After:=Cells(1, 1))
RngUserNameHeader.EntireColumn.Insert
RngUserNameHeader.Offset(0, -1).Value = "TRIM CONTRACT"
RngUserNameHeader.Offset(0, -1).Font.Bold = True
Dim lastRow As Long
lastRow = RngUserNameHeader.Offset(Rows.Count - 1, 0).End(xlUp).Row
BuiltFormula = "=TRIM(" & Replace(RngUserNameHeader.Offset(1, 0).Address, "$", "") & ")"
RngUserNameHeader.Offset(1, -1).Resize(lastRow).Formula = BuiltFormula
End Sub

Add comment to cell if cell in other column contains value

I have a code that combines the cell contents of all cells in column C:F and puts that into a comment on column B - per row.
I now need to apply that only to rows that have content in their respective column A.
Cell A2 has something in it, so put the contents of C2:F2 into the comment of B2.
Cell A3 has nothing in it, so don't add a comment to that cell.
Cell A4 has something in it again, so put the contents of C4:F4 into the comment of B4.
The table looks something like this: Table
My code so far looks like this:
Sub Test()
Dim LRow As Integer
With ActiveSheet
For LRow = 2 To Range("A" & Rows.Count).End(xlUp).Row
Range(Cells(LRow, 3), Cells(LRow, 6)).Select
Dim c As Range, s As String
With Cells(LRow, 2)
.ClearComments
For Each c In Selection
'If c.Offset(0, -2) <> "" Then
'On Error Resume Next
If c <> "" Then s = IIf(s = "", c, s & Chr(10) & c)
Next c
.AddCommentThreaded "Test:" & Chr(10) & s
End With
s = ""
Next LRow
End With
End Sub
Problem now being that I can't get the content check in column A to work. Anyone have any hints on how to get that bit to work?
Try something like below. Also checkout how to avoid select and why use long instead of integer
Sub Test()
Dim LRow As Long, aCell As Range, ws As Worksheet
Set ws = ActiveSheet
With ws
For LRow = 2 To .Cells(Rows.Count, 1).End(xlUp).Row
If .Cells(LRow, 1).Value <> "" Then
Dim theComment As String
theComment = ""
For Each aCell In Intersect(Range("C:F"), .Rows(LRow)).Cells
theComment = theComment & aCell.Value
Next aCell
With .Cells(LRow, 2)
.ClearComments
.AddCommentThreaded "Test:" & Chr(10) & theComment
End With
End If
Next LRow
End With
End Sub

copy data from sheet to sheet with multiple criteria

I want to copy data from sheet 2 to sheet 5 with multiple criteria.
example data:
I wrote the following code ...
Dim myrange As Range
Set myrange = Worksheets("Sheet2").Range("a1:k50")
myrange.Parent.AutoFilterMode = False
myrange.AutoFilter field:=1, criteria1:="=Monitors"
myrange.AutoFilter field:=2, criteria1:="=Jul-19"
myrange.AutoFilter field:=3, criteria1:="=1"
myrange.AutoFilter field:=5, criteria1:="=P"
myrange.Parent.AutoFilter.Range.Copy
With Sheet5.Range("a10")
.PasteSpecial Paste:=8
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
.Select
End With
myrange.Parent.AutoFilterMode = False
When I run the code it copies headings only.
the output should be.
Any thoughts?
I'd do in a slightly different way, as I'm not too into using filters in macros.
Please note this code will paste in Sheet5 last row. Feel free to adapt it to your needs.
Also, please note using dates (like "Jul-19") in this format could cause you some issues. Try to convert it (on the code below) to a value depending on your original table's format:
Sub testStackOverflow()
Dim myrange As Range
Dim Criteria1 As String
Dim Criteria2 As String
Dim Criteria3 As String
Dim Criteria4 As String
Set myrange = Worksheets("Sheet2").Range("A1:A50")
Criteria1 = "Monitors"
Criteria2 = "Jul-19"
Criteria3 = "1"
Criteria4 = "P"
For Each SearchCell In myrange
Debug.Print SearchCell.Value
If SearchCell.Value = Criteria1 Then
If SearchCell.Offset(0, 1).Value = Criteria2 Then
If SearchCell.Offset(0, 2).Value = Criteria3 Then
If SearchCell.Offset(0, 4).Value = Criteria4 Then
LastRow = Sheets("Sheet5").Range("A1048576").End(xlUp).Row + 1
Sheets("Sheet5").Range("A" & LastRow).Value = SearchCell.Value
Sheets("Sheet5").Range("B" & LastRow).Value = SearchCell.Offset(0, 1).Value
Sheets("Sheet5").Range("C" & LastRow).Value = SearchCell.Offset(0, 2).Value
Sheets("Sheet5").Range("D" & LastRow).Value = SearchCell.Offset(0, 3).Value
Sheets("Sheet5").Range("E" & LastRow).Value = SearchCell.Offset(0, 4).Value
End If
End If
End If
End If
Next SearchCell
End Sub

Code to compare to columns, find differences, and paste them in a new column

I'm just trying to compare columns A and D and see if there is any value in A that is not in D. Then, I want to copy that value and the adjacent cell, Column B, and paste them in Columns G and H.
For example, in the photo, the expected outcome would be wilsona in G3 and Last, First2 in H3. The number of rows will be variable and A and D will probably never have the same number of rows.
All I have is the code below. The issue is it is only comparing, for example, A1 to D1 instead of to the entire range of D:
Dim i As Integer
i = 1
For i = 3 To 20
If (Range("A" & i).Select <> Range("D" & i).Select) Then
Range("A" & i).Select
Selection.Copy
Range("G" & i).Select
ActiveSheet.Paste
Range("B" & i).Select
Selection.Copy
Range("H" & i).Select
ActiveSheet.Paste
End If
Next i
Example:
This should work for your scenario:
Sub Macro1()
Dim ws as Worksheet
set ws = ThisWorkbook.Worksheets("Compare")
Dim rngA As Range, rngD as Range, MySel as Range
Set rngA = ws.Range("A3", Range("A" & Rows.Count).End(xlUp))
Set rngD = ws.Range("D3", Range("D" & Rows.Count).End(xlUp))
For Each cell In rngA
If IsError(Application.Match(cell.Value, rngD, 0)) Then
If MySel Is Nothing Then
Set MySel = cell.Resize(1,2)
Else
Set MySel = Union(MySel, cell.Resize(1,2))
End If
End If
Next cell
If Not MySel Is Nothing Then MySel.Copy Destination:= ws.Range("G3")
End Sub

How to copy the contents of two cells dynamically?

Right now my program works. But, I need to copy another cell that's next to the cell being copied when a match is found. I go through myrange1 and when I find a match in myrange2, I copy the contents from Column A in Sheet1 from whichever cell it's at. I want column B, same cell index, to be copied and pasted as well. My copied data is getting pasted in Column(s) R:S. of Sheet2. Column R is the numbers and S is the data.
Sub matchcopy()
Dim i&
Dim myrange1 As Range, myrange2 As Range, myrange3 As Range, cell As Range
' You can use the Codenames instead of Worksheet("Sheet1") etc.
Set myrange1 = Sheet1.Range("A1", Sheet1.Range("A" & Rows.Count).End(xlUp))
Set myrange2 = Sheet2.Range("A1", Sheet2.Range("A" & Rows.Count).End(xlUp))
Set myrange3 = Sheet2.Range("B1", Sheet2.Range("B" & Rows.Count).End(xlUp))
Sheet2.Range("R:S") = "" ' <~~ clear result columns
For Each cell In myrange1 ' presumably unique items
If Not IsError(Application.Match(cell.Value, myrange2, 0)) Then
'Sheet2.Cells(i, 2).Offset(, 1).Resize(1, 1).Copy
cell.Copy
With Sheet2.Range("R50000").End(xlUp)
i = i + 1 ' <~~ counter
.Offset(1, 0) = i ' counter i equals .Row - 1
.Offset(1, 1).PasteSpecial xlPasteFormulasAndNumberFormats
End With
Else
'MsgBox "no match is found in range"
End If
Next cell
Sheet2.Columns("R:S").EntireColumn.AutoFit
Call Set_PrintRnag
End Sub
Sub Set_PrintRnag()
Dim LstRw As Long
Dim Rng As Range
Dim strDesktop As String
Application.ScreenUpdating = True
strDesktop = CreateObject("WScript.Shell").SpecialFolders("Desktop")
LstRw = Sheet2.Cells(Rows.Count, "R").End(xlUp).Row
Set Rng = Sheet2.Range("R1:S" & LstRw)
With Sheet2.PageSetup
.LeftHeader = "&C &B &20 Cohort List Report:" & Format(Now, "mm/dd/yyyy")
.CenterFooter = "Page &P of &N"
.CenterHorizontally = False
.FitToPagesWide = 1
.RightFooter = ""
End With
Rng.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strDesktop & "\CohortList " & " " & Format(Date, "mm-dd-yyyy") & ".pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
https://learn.microsoft.com/en-us/office/vba/api/excel.range.offset
You have a cell in column 'A' BUT you want same row in column 'B'.
cell.Offset(0,1).value = cell.value

Resources