Excel VBA to Copy Column from one sheet to another based on a second columns cell value - excel

I tried this, which returned the rows I want, so a good start. But I really just need the value in Column B, not the entire row. What I really want is to list the value in column B if the value in column C is <>"" and column D <>"". Results in Quote sheet starting in cell C4.
Sub CopyQuoteValues()
Dim xRg As Range
Dim xCell As Range
Dim A As Long
Dim B As Long
Dim C As Long
A = Worksheets("Software Options").UsedRange.Rows.Count
B = Worksheets("Quote").UsedRange.Rows.Count
If B = 1 Then
If Application.WorksheetFunction.CountA(Worksheets("Quote").UsedRange) = 0 Then B = 0
End If
Set xRg = Worksheets("Software Options").Range("C17:C" & A)
On Error Resume Next
Application.ScreenUpdating = False
For C = 1 To xRg.Count
If CStr(xRg(C).Value) <> "" Then
xRg(C).EntireRow.Copy Destination:=Worksheets("Quote").Range("A" & B + 1)
B = B + 1
End If
Next
Application.ScreenUpdating = True
End Sub

Something like this should do what you need:
Sub CopyQuoteValues()
Dim wsOpt As Worksheet, wsQuote As Worksheet
Dim c As Range, rngDest As Range
Set wsOpt = Worksheets("Software Options")
Set wsQuote = Worksheets("Quote")
Set rngDest = wsQuote.Range("C4")
For Each c In wsOpt.Range("C17", wsOpt.Cells(wsOpt.Rows.Count, "C").End(xlUp)).Cells
If Len(c.Value) > 0 And Len(c.Offset(0, 1)) > 0 Then 'value in C and D ?
c.Offset(0, -1).Copy rngDest 'copy ColB
Set rngDest = rngDest.Offset(1, 0) 'next paste location
End If
Next c
End Sub

Related

I cannot get my macro to loop through columns to perform the action I need

I have created a macro that checks row 3 in column B for two different criteria and if either are met, it puts the letter "R" in empty cells in the range B5:B20. If all are empty it dumps the word "No" in cell B34. I need this to do the same operation in columncs C to AF but I can't get it to loop. Any help would be appreciated. Thank you.
Sub Column_B()
Dim ws As Worksheet
Dim b As Range
Set ws = Worksheets("January")
For Each b In Range("B5:B20")
If b.Value = 0 And ws.Range("b3") = ws.Range("a34") Or b.Value = 0 And ws.Range("b3") = ws.Range("a35") Then
b.Value = "R"
Else
ws.Range("b34") = "No"
End If
Next b
End Sub
Iterate across the columns B to AF in row 3 and use offsets to loop through the rows 5 to 20.
Option Explicit
Sub Column_BtoAF()
Dim ws As Worksheet, r As Long
Dim cell As Range, c As Range, bEmpty As Boolean
Set ws = Worksheets("January")
For Each c In Range("B3:AF3").Cells
If c.Value2 = ws.Range("A34").Value2 _
Or c.Value2 = ws.Range("A35").Value2 Then
bEmpty = True
For r = 5 To 20
Set cell = c.Offset(r - 3)
If IsEmpty(cell) Then
cell.Value = "R"
Else
bEmpty = False
End If
Next
If bEmpty Then c.Offset(31) = "No" ' row 34
End If
Next
MsgBox "Done"
End Sub

How Do I Add 3rd Range to Reconcile?

I'm looking to create a tool which will reconcile values across 3 spreadsheets. For example, Sheet1: ID = 123A, Country = IRELAND; Sheet2: ID = 123A, COUNTRY = UK; Sheet3: ID = 123A, COUNTRY = UK. If it does not match, we will get a FALSE value.
Currently, I have the capacity to reconcile 2 files in columns B & C in shtRecon and am looking to add a 3rd value in column D which will reconcile 3 files instead of 2.
In other words, when column B = column C, there are 0 errors, when column B <> column C, there is 1 error. I'd like it to be column B = column C = column D instead. I've included my working code for 2 column reconciliation beneath. Any ideas?
Sub ReconcileVenueRef()
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim shtRecon As Worksheet
Dim shtSummary As Worksheet
Dim rng1 As Range
Dim rng2 As Range
Dim cel As Range
Dim oDict As Object
Dim reconRow As Long
Dim noOfErrors As Long
Dim ETL As Variant
Dim MiFID As Variant
Dim Match As Boolean
Set sht1 = Worksheets("MiFID Export")
Set sht2 = Worksheets("ETL")
Set shtRecon = Worksheets("Reconciliation")
Set shtSummary = Worksheets("Summary")
'Define the columns that you need, and find the last row
Set rng1 = sht1.Range("A2:B" & sht1.Range("A" & sht1.Rows.Count).End(xlUp).Row)
Set rng2 = sht2.Range("A2:B" & sht2.Range("A" & sht2.Rows.Count).End(xlUp).Row)
'Get a dictionary object holding unique values from sheet 2
'In my case, column A holds the Id, and column B holds the value
Set oDict = GetDictionary(rng2, 1, 4)
reconRow = 0
'Loop over each cel in sheet 1, column 1
'Look for the value in column 1 in the sheet 2 dictionary
'object, and then reconcile
For Each cel In Intersect(rng1, sht1.Columns(1))
'Get the next avail row in reconciliation sheet
reconRow = reconRow + 1
shtRecon.Range("A" & reconRow).Value = cel.Value
'Recon column B holds value from sheet 1, column B
shtRecon.Range("B" & reconRow).Value = cel.Offset(, 3).Value
'If Id is found in Sheet B dictionary, then take the value
'otherwise, write "blank" in column C
'ETL spreadsheet
If oDict.exists(cel.Value) Then
shtRecon.Range("C" & reconRow).Value = oDict(cel.Value)
Else
shtRecon.Range("C" & reconRow).Value = "BLANK"
End If
Next cel
'If ETL cell = MiFID cell then noOfErrors is 0, otherwise it's 1
noOfErrors = 0
ETL = shtRecon.Cells(1, 3).Value
MiFID = shtRecon.Cells(1, 2).Value
If ETL = MiFID Then
Match = True
shtRecon.Cells(1, 4).Value = Match
shtSummary.Cells(4, 3).Value = noOfErrors
ElseIf ETL <> MiFID Then
Match = False
shtRecon.Cells(1, 4).Value = Match
noOfErrors = noOfErrors + 1
shtSummary.Cells(4, 3).Value = noOfErrors
End If
End Sub
'Function stores a range into a dictionary
'Param inputRange takes a range to be stored
'Param idColumn takes the column of the range to be used as the ID
'e.g. if idColumn = 2, and inputRange("C1:F10"), then column D is used for ID
'Param valueColumn points to the column in range used for the value
Function GetDictionary(inputRange As Range, idColumn As Long, valueColumn As Long) As Object
Dim oDict As Object
Dim sht As Worksheet
Dim cel As Range
Set oDict = CreateObject("Scripting.Dictionary")
Set sht = inputRange.Parent
For Each cel In Intersect(inputRange, inputRange.Columns(idColumn))
If Not oDict.exists(cel.Value) Then
oDict.Add cel.Value, sht.Cells(cel.Row, valueColumn).Value
End If
Next cel
Set GetDictionary = oDict
End Function

Loop throughDv (change cell when h > a)

I have the following code:
Sub LoopThroughDv()
Dim dvCell As Range
Dim inputRange As Range
Dim c As Range
Dim i As Long
Dim h As Range
Dim a As Range
Set h = Worksheets("Ark2").Range("H2")
Set a = Worksheets("Ark2").Range("A2")
'Which cell has data validation
Set dvCell = Worksheets("Ark2").Range("I2")
'Determine where validation comes from
Set inputRange = Evaluate(dvCell.Validation.Formula1)
i = 0
'Begin our loop
Application.ScreenUpdating = True
For Each c In inputRange
dvCell = c.Value
i = i + 1
If h > a Then
Exit For
End If
Next c
Application.ScreenUpdating = True
End Sub
and when h > a i want to change h,a and dvCell to cell H3, A3, and I3 and then continue increasing until blank cell.
Something like the below? The point is you have to loop the entire process until you get the blank cell. You may need to adjust the until portion a bit according to your data setup.
i = 2
Do
Set h = Worksheets("Ark2").Range("H" & i)
Set a = Worksheets("Ark2").Range("A" & i)
'Which cell has data validation
Set dvCell = Worksheets("Ark2").Range("I" & i)
'Determine where validation comes from
Set inputRange = Evaluate(dvCell.Validation.Formula1)
For Each c In inputRange
dvCell = c.Value
If h.Value > a.Value Then Exit For
Next c
i = i + 1
Loop Until h.Offset(1).Value = ""

Excel: VBA to copy values to specific row

I currently have a macro that copies the value from a specific cell from one sheet(BACKEND), and pastes in specific column in another sheet (EXPORT_DATA), in the next blank row.
Sub copy_values(Optional Source As String = "A1", Optional Source2 As String = "A1")
Dim R As Range
Dim col As Long
col = Range(Source).Column
Set R = Worksheets("EXPORT_DATA").Cells(Rows.Count, col).End(xlUp)
If Len(R.Value) > 0 Then Set R = R.Offset(1)
R.Value = Worksheets("BACKEND").Range(Source2).Value
End Sub
It works well, but I want to replace the the function in where it pastes the data in the next blank cell in a column, to a function in where it pastes the data in a row in where a cell holds a specified value.
For example, the older function would do the following
step 1:
c1 c2 c3
a b 4
c d 6
step 2 (after macro executed):
c1 c2 c3
a b 4
c d 6
c d 5
But I need a new function that does this:
step 2 (C1 value of "c" specified, macro executed):
c1 c2 c3
a b 4
c d 5
See how this goes for you. Not sure how you are calling etc but it should be a reasonable starting point. I only gave it a really quick test
Sub copy_values_SINGLE(cValue As Variant, Optional Source As String = "A1", Optional Source2 As String = "A1")
' Not sure of what value type c in your question would be but expects a single value to test against the column provided as Source
' Requires cValue to be provided
Dim R As Range
Dim col As Long
Dim destRow As Integer
col = Range(Source).Column
On Error Resume Next
destRow = 0
destRow = Worksheets("EXPORT_DATA").Columns(col).Find(cValue, SearchDirection:=xlPrevious).Row
If destRow = 0 Then destRow = Worksheets("EXPORT_DATA").Cells(Rows.Count, col).End(xlUp).Row + 1 ' if cValue isnt found reverts to the last row as per previous code
On Error GoTo 0
Set R = Worksheets("EXPORT_DATA").Cells(destRow, col)
R.Value = Worksheets("BACKEND").Range(Source2).Value
End Sub
This may work
Sub copy_values(Optional Source As String = "A1", Optional Source2 As String = "A1")
Dim R As Variant
Dim col As Long
col = Range(Source).Column
Dim mrn As String
Dim FoundCell As Excel.Range
Dim myVal As String
R = Worksheets("BACKEND").Range(Source2).Text
myVal = Worksheets("BACKEND").Range(Source2).Text
mrn = Worksheets("BACKEND").Range("A5").Value
Set FoundCell = Worksheets("EXPORT_DATA").Range("A:A").Find(what:=mrn, lookat:=xlWhole, searchdirection:=xlPrevious)
If Not FoundCell Is Nothing Then
' MsgBox (R & " " & col & " " & FoundCell.Row)
Worksheets("EXPORT_DATA").Range("Q" & FoundCell.Row).Value = R
Else
MsgBox "error"
End If
End Sub
Still not 100% certain, but I think this is what you are after. The file loop all values in column A of the EXPORT_DATA file and compared them to the value in cell A1 of the BACKEND worksheet. If it finds the value it replaces the value in column B, if it cannot find the value, it adds it at the end:
Sub copy_values_SINGLE()
Dim R As Range
Dim rowCount As Long
Dim varValue As Variant
rowCount = Application.WorksheetFunction.CountA(Worksheets("EXPORT_DATA").Range("A:A"))
For s = 1 To rowCount
If Worksheets("EXPORT_DATA").Range("A" & s).Value = Worksheets("BACKEND").Range("A1").Value Then
Worksheets("EXPORT_DATA").Range("A" & s & ":B" & s).Value = Worksheets("BACKEND").Range("A1:B1").Value
Exit For
Else
If s = rowCount Then
Set R = Worksheets("EXPORT_DATA").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
R.Value = Worksheets("BACKEND").Range("A1:B1").Value
End If
End If
Next s
End Sub
Let me know if this works for you.

Retrieve Column header depending on values present in an excel worksheet

I have two worksheets ( sheet 1 and sheet 2) . Sheet 1 has 500X500 table. I want to
- Loop through each row ( each cell )
- Identify the cells which have a value ' X' in it
- Pick the respective column header value and store it in a cell in worksheet 2
For example
AA BB CC DD EE FF GG HH
GHS X
FSJ X
FSA X
MSD
SKD
SFJ X X
SFJ
SFM X
MSF X
Is there a way of writing a macro which will pull values in the form of
GHS -> GG
FSJ->DD
.
.
SFJ->BB HH
I have tried looping algorithms but does not seem to work. Could anyone please help me as I am very new to macros.
Try this .. Assumed that GHS, FSJ ... in column A
Sub ColnItem()
Dim x, y, z As Integer
Dim sItem, sCol As String
Dim r As Range
z = 1
For y = 1 To 500
sItem = Cells(y, 1)
sCol = ""
For x = 2 To 500
If UCase(Cells(y, x)) = "X" Then
If Len(sCol) > 0 Then sCol = sCol & " "
sCol = sCol & ColumnName(x)
End If
Next
If Len(sCol) > 0 Then
Sheets("Sheet2").Cells(z, 1) = sItem & " -> " & sCol
z = z + 1
End If
Next
End Sub
Function ColumnName(ByVal nCol As Single) As String
Dim sC As String
Dim nC, nRest, nDivRes As Integer
sC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nC = Len(sC)
nRest = nCol Mod nC
nDivRes = (nCol - nRest) / nC
If nDivRes > 0 Then ColumnName = Mid(sC, nDivRes, 1)
ColumnName = ColumnName & Mid(sC, nRest, 1)
End Function
I have placed the values GG, etc., in separate columns of Sheet2, but the code could be modified to put all the information (for a row) in a single cell.
Sub GetColumnHeadings()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim rng1 As Range, rng2 As Range, rng As Range
Dim off As Integer
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
Set rng1 = ws1.Range("A1").CurrentRegion
'CurrentRegion is the Range highlighted when we press Ctrl-A from A1
Set rng2 = ws2.Range("A1")
Application.ScreenUpdating = False
For Each rng In rng1
If rng.Column = 1 Then off = 0
If rng.Value = "X" Then
rng2.Value = rng.EntireRow.Cells(1, 1).Value
off = off + 1
rng2.Offset(0, off).Value = rng.EntireColumn.Cells(1, 1).Value
End If
'if we are looking at the last column of the Sheet1 data, and
'we have put something into the current row of Sheet2, move to
'the next row down (in Sheet2)
If rng.Column = rng1.Column And rng2.Value <> "" Then
Set rng2 = rng2.Offset(1, 0)
End If
Next rng
Application.ScreenUpdating = True
Set rng = Nothing
Set rng2 = Nothing
Set rng1 = Nothing
Set ws2 = Nothing
Set ws1 = Nothing
End Sub
I've also based in on the spreadsheet sample from the original post, where AA appears to be in cell A1.

Resources