matching values in cells to Named ranges - vba - vba

I am using VBA to try to see if values in cells from one workbook match the named ranges from another workbook and if they do match then copy paste values from another column in those named ranges. I know they will match. the purpose is just to copy the values over into their designated named range.
The problem is in this line:
If rng = ws2.Range("NamedRange") Then
Here is my code below:
Sub Button4_Click()
Dim strFileName As String
Dim wb1 As Workbook
Dim ws1 As Worksheet
Dim wb2 As Workbook
Dim ws2 As Worksheet
Dim cell As Range
Dim rng As Range
Dim RangeName As String
Dim CellName As String
''Set wb2 = ActiveWorkbook
''Set ws2 = wb2.Sheet("Output")
''ws2.Range("D1:D12").Copy
''Set wb1 = ActiveWorkbook
strFileName = CreateObject("WScript.Shell").specialfolders("Desktop") & "\BAC GVP - Template_Update_121917.xlsm"
If Dir(strFileName) <> vbNullString Then
Set wb1 = Workbooks.Open(strFileName)
Else
MsgBox "Sorry, the file does not exist on your Desktop at this time, please drop a copy to your Desktop from server!"
End If
''Set wb2 = ThisWorkbook
''Set ws2 = wb2.Sheets("Output")
''Set ws1 = wb1.Sheets("RVP Local GAAP")
''ws2.Range("D4:D12").Copy
''ws1.Range("G13:G21").PasteSpecial xlPasteValues
''RangeName = "myData"
''CellName = "G11:G83"
''Set cell = Worksheets("RVP Local GAAP").Range(CellName)
''ThisWorkbook.Names.Add Name:=RangeName, RefersTo:=cell
''RangeName = "NamedRange"
''CellName = "C4:C12"
Set wb2 = ThisWorkbook
Set ws2 = wb2.Sheets("Output")
Set ws1 = wb1.Sheets("RVP Local GAAP")
For Each rng In ws1.Range("CurrentTaxPerLocalGAAPProvision")
If rng = ws2.Range("NamedRange") Then
ws2.Range("ReportBalance").Copy
ws1.Range("CurrentTaxPerLocalGAAPProvision").PasteSpecial xlPasteValues
MsgBox "Values Copied Successfully"
End If
Next rng
MsgBox "Both Ranges do not have the same data"
End Sub
See image below - Cell G29 is called "GVP_Donations_CurrentTaxPerLocalGAAPProvision"... so for this example I would want $4,313 to appear in the cell G29
CurrentTaxPerLocalGAAPProvision:
Range ("NameRange"):

Your line saying
If rng = ws2.Range("NamedRange") Then
is crashing out due to the attempt to compare the value of rng (e.g. "" when rng is referring to the cell G29) with an array of values (the values in "NamedRange"). VBA cannot handle the comparison of a scalar to a vector. But it isn't what you are wanting to do anyway.
I believe that, to do what it seems you are trying to do, you can replace your loop with:
'Loop through all the values in NamedRange
For Each rng In ws2.Range("NamedRange")
'Transfer the value from the next column to the appropriate range in the
'destination sheet
ws1.Range(rng.Value).Value = rng.Offset(0, 1).Value
Next
MsgBox "Values Copied Successfully"
If only some of the values in "NamedRange" should be copied, then you may need to include a bit of testing to see whether the ranges are in the correct target area:
Dim dstRng As Range
'Loop through all the values in NamedRange
For Each rng In ws2.Range("NamedRange")
Set dstRng = Nothing
On Error Resume Next
Set dstRng = ws1.Range(rng.Value)
On Error GoTo 0
'Check that the range exists in destination sheet
If Not dstRng Is Nothing Then
'Check that the range exists in the appropriate area
If Not Intersect(dstRng, ws1.Range("CurrentTaxPerLocalGAAPProvision")) Is Nothing Then
'Transfer the value from the next column to the appropriate range in the
'destination sheet
dstRng.Value = rng.Offset(0, 1).Value
End If
End If
Next
MsgBox "Values Copied Successfully"

Related

When copy and pasting a range, the open workbook is selected incorrectly using a with statement in VBA

I am trying to copy the range from one worksheet and paste it into another workbook and then do the same for another range in a different workbook. The issue I am having is it is taking what seems to be taking the range from the "most recently opened" workbook rather than selecting the correct one.
See below the following code:
Sub CopyTEST()
Dim Wb1 As Workbook, wb2 As Workbook, wb3 As Workbook, wB As Workbook
Dim rngToCopy1 As Range, rngToCopy2 As Range
Dim wbName1 As String, wbName2 As String
wbName1 = "Book"
wbName2 = "APP"
For Each wB In Application.Workbooks
If wB.Name Like wbName2 & "*" Then
Set Wb1 = wB
Debug.Print Wb1.Name
End If
If wB.Name Like wbName1 & "*" Then
With wB.Sheets("Sheet1")
If Left(Right(Cells(6, 4), 4), 2) = "12" Then
MsgBox ("12")
Set wb2 = wB
ElseIf Left(Right(Cells(6, 4), 4), 2) = "10" Then
MsgBox ("10")
Set wb3 = wB
Set wb3 = wB
Else
MsgBox ("ERROR")
Exit Sub
End If
End With
End If
Next wB
With wb2.Sheets("Sheet1")
Set rngToCopy1 = .Range("A1:II82")
End With
With wb3.Sheets("Sheet1")
Set rngToCopy2 = .Range("A1:II82")
End With
With Wb1
.Sheets("A").Range("A1:II82").Value = rngToCopy2.Value
.Sheets("B").Range("A1:II82").Value = rngToCopy1.Value
End With
End Sub
The issue I am seeming to have is say we have Book3 where the cells are equal to 12 and then Book4 where the cells are equal to 10. If Book4 is directly open then when we are going through the For loop with each wB, and we are observing Book3, it will take the range from Book4 instead of Book3...
The If statements obvserving the cells in the worksheets are showing correct values when I step into the code, they are just selecting the wrong ranges...
I hope this makes sense... Thanks!
You are not carrying the parent reference you created on to the cells.
With wB.Sheets("Sheet1")
If .Cells(6, 4) = "12" Then
MsgBox ("12")
Set wb2 = wB
ElseIf .Cells(6, 4) = "10" Then
MsgBox ("10")
Set wb3 = wB
Else
MsgBox ("ERROR")
Exit Sub
End If
End With
Note .Cells not Cells. This transfers the workbook/worksheet from the With ... End With to .Cells.

Match columns in 2 worksheets and paste to a third worksheet

I have numbers in no specific order on 2 worksheets (wb1 and wb2). If there is a match, I need the email address in column b on wb2 to paste to the worksheet wb3 in column A. The code I have below only matches the numbers if they are in the same cells on both worksheets. Any help is greatly appreciated.
Private Sub CommandButton2_Click()
'Merge Report button
Dim foundCell As Range
Dim strFind As String
Dim fRow, fCol As Integer
Dim wb1 As Worksheet
Dim wb2 As Worksheet
Dim wb3 As Worksheet
'Set sheets - wb1 is email list and wb2 is missed punch report, and wb3 is home page
Set wb1 = Sheets("Sheet1")
Set wb2 = Sheets("Sheet1 (2)")
Set wb3 = Sheets("Home")
'Get find string
strFind = wb1.Range("A1").Value
'Find string in column C of Sheet2
Set foundCell = wb2.Range("A1").Find(strFind, LookIn:=xlValues)
'If match cell is found
If Not foundCell Is Nothing Then
'Get the row and column
fRow = foundCell.Row
fCol = foundCell.Column
'copy email from column b
wb1.Range("B1").Copy
'paste in column a on home page
wb3.Range("A1").PasteSpecial xlPasteValues
'Clear cache
Application.CutCopyMode = False
'If not found, show message.
Else
Call MsgBox("No match was found. Clear form and start over with step 1.")
End If
End Sub

1004 error for using usedrange

I am trying to copy over values from one workbook to another using the usedrange function (there are some blanks in certain rows and it is fine to copy over the blank as well), but I am getting the 1004 error:
Sub ActiveInactiveVendors()
Dim ActiveWkb As Workbook, Wkb As Workbook, InactiveWkb As Workbook
Dim ActiveWkst As Worksheet, Wkst As Worksheet, InactiveWkst As Worksheet
Dim aCell As Range
Dim targetRng As Range
Set ActiveWkb = Workbooks.Open("C:\Users\clara\Desktop\active vendors.xlsx")
Set Wkb = ThisWorkbook
Set Wkst = Wkb.Sheets("Vendors")
Set ActiveWkst = ActiveWkb.Worksheets("aqlc7da48e7")
'set column A starting from A7
Set targetRng = Wkst.Range("A7" & Wkst.Rows.Count)
'get the values starting from a32 to the last row used and set it in wkst
targetRng.Value = ActiveWkst.Range("A32" & ActiveWkst.UsedRange.Rows.Count).Value
End Sub
I appreciate any feedback! Thank you
This line:
Set targetRng = Wkst.Range("A7" & Wkst.Rows.Count)
is not correct. You are not getting A7:A1048576 but a concatenating of the two. So it is looking for A71048576 which does not exist
Then you should use similar sized ranges when setting values.
Sub ActiveInactiveVendors()
Dim ActiveWkb As Workbook, Wkb As Workbook, InactiveWkb As Workbook
Dim ActiveWkst As Worksheet, Wkst As Worksheet, InactiveWkst As Worksheet
Dim aCell As Range
Dim targetRng As Range, origRng As Range
Set ActiveWkb = Workbooks.Open("C:\Users\clara\Desktop\active vendors.xlsx")
Set Wkb = ThisWorkbook
Set Wkst = Wkb.Sheets("Vendors")
Set ActiveWkst = ActiveWkb.Worksheets("aqlc7da48e7")
'set column A starting from A7
Set origRng = ActiveWkst.Range("A32", ActiveWkst.Cells(ActiveWkst.Rows.Count, 1).End(xlUp))
Set targetRng = Wkst.Range("A7", Wkst.Cells(origRng.Rows.Count + 6, 1))
'get the values starting from a32 to the last row used and set it in wkst
targetRng.Value = origRng.Value
End Sub

Excel Macro to name ranges according to the name of the worksheet Tab name

I have the following code which I am trying to get to name the entire A and B columns range according to the worksheet tab name. I want each A:B range of cells in each worksheet to be named RoomCode_ + the name of the excel sheet tab.
So for example if I had 3 sheets called XYZ, ABC and DEF, then my cell range names for those 3 sheets respectively should be:
RoomCode_XYZ
RoomCode_ABC
RoomCode_DEF
I would typically do this manually by highlighting the cell range and just typing the range name I wanted, however I have over 150 tabs and would like to be able to do them all automatically through this process.
Sub nameRanges()
Set wbook = ActiveWorkbook
For Each sht In wbook.Worksheets
sht.Activate
RangeName = "RoomCode_" + ActiveSheet.Name
CellName = "A:B"
Set cell = ActiveWorksheets.Range(CellName)
ActiveWorksheets.Names.Add Name:=RangeName, RefersTo:=cell
Next sht
End Sub
Just a bit of refactoring to get what you need. Biggest this to work directly with objects and eliminate the Active... stuff.
Also ActiveWorksheets is not proper syntax in any way.
Sub nameRanges()
Dim wbook As Workbook
Set wbook = ThisWorkbook
Dim sht As Worksheet
For Each sht In wbook.Worksheets
Dim RangeName As String, CellName As String
RangeName = "RoomCode_" + sht.Name
CellName = "A:B"
Dim cell As Range
Set cell = sht.Range(CellName)
sht.Names.Add Name:=RangeName, RefersTo:=cell
Next sht
End Sub
Here's another way:
Option Explicit
Sub nameRanges()
Dim sht As Worksheet
Dim RangeName As String
Dim cell As String
For Each sht In ActiveWorkbook.Worksheets
RangeName = "RoomCode_" + sht.Name
cell = "=" & sht.Name & "!" & "A:B"
Names.Add Name:=RangeName, RefersTo:=cell
Next sht
End Sub
I think that you would want to add the names to the workbook names collection. The way it is now you'll still have to reference the individual worksheet before you can access the name.
WorkSheets("RoomCode").Range("RoomCode_XYZ")
By adding the names to the workbook you'll be able to access no matter the ActiveSheet.
Range("RoomCode_XYZ")
Sub nameRanges()
Dim wbook As Workbook
Set wbook = ThisWorkbook
Dim sht As Worksheet
For Each sht In wbook.Worksheets
Dim RangeName As String, CellName As String
RangeName = "RoomCode_" + sht.Name
CellName = "A:B"
Dim cell As Range
Set cell = sht.Range(CellName)
ThisWorkBook.Names.Add Name:=RangeName, RefersTo:=cell
Next sht
End Sub

Error at attempt to copy data from external workbook with several worksheets to another workbook

The problem: I am trying to copy data from one workbook to another.
Lets say I have a workbook (called DATA) with several worksheets filled with data. Each column of data has a unique heading (all headings on the same row).
On the other hand I have another workbook (called REPORT) with one worksheet that contains only the heading of the data (in one row). They are not in the same order as in DATA workbook. For example I have 3 headings in REPORT worksheet that can be found in different worksheets in DATA workbook.
I need to loop through all the worksheets in the DATA workbook and copy paste the whole column to the REPORT worksheet when the same heading is found.
This image may help to understand. Explanation
My first attempt:
Dim MyFile As String
Dim ws As Worksheet
''Workbook that contains one worksheet with all the headings ONLY NO DATA
Dim TargetWS As Worksheet
Set TargetWS = ActiveSheet
Dim TargetHeader As Range
''Location of Headers I want to search for in source file
Set TargetHeader = TargetWS.Range("A1:G1")
''Source workbook that contains multiple sheets with data and headings _
not in same order as target file
Dim SourceWB As Workbook
Set SourceWB = Workbooks("Source.xlsx")
Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
Dim SourceCell As Range
''Stores the col of the found value and the last row of data in that col
Dim RealLastRow As Long
Dim SourceCol As Integer
''Looping through all worksheets in source file, looking for the heading I want _
then copying that whole column to the target file I have
For Each ws In SourceWB.Sheets
ws.Activate
For Each Cell In TargetHeader
If Cell.Value <> "" Then
Set SourceCell = Rows(SourceHeaderRow).Find _
(Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not SourceCell Is Nothing Then
SourceCol = SourceCell.Column
RealLastRow = Columns(SourceCol).Find("*", LookIn:=xlValues, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If RealLastRow > SourceHeaderRow Then
Range(Cells(SourceHeaderRow + 1, SourceCol), Cells(RealLastRow, _
SourceCol)).Copy
TargetWS.Cells(2, Cell.Column).PasteSpecial xlPasteValues
End If
End If
End If
Next
Next
I am getting an error of Application-defined or object-defined error Run-time 1004. Is there something wrong with my logic/syntax..?
Please help I am so bad in VBA.
Thanks in advance!
your last edited code works
but you're making unnecessary checks and I'd suggest you to loop through each sheet header and check if it exists in TargetHeader range to possibly subsequently copy its column to SourceWB
furthermore you may want to have your code more robust and check for actual wanted workbooks/worksheets existence before attempting to set variables to them
like follows:
Option Explicit
Sub main()
Dim SourceWB As Workbook
Dim ws As Worksheet, TargetWS As Worksheet
Dim TargetHeader As Range, cell As Range, SourceCell As Range
Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
''Source workbook that contains multiple sheets with data and headings _
not in same order as target file
Set SourceWB = GetWb("Source.xlsx")
If SourceWB Is Nothing Then Exit Sub
''Workbook that contains one worksheet with all the headings ONLY NO DATA
'Set TargetWS = ActiveSheet
Set TargetWS = GetWs("REPORT") 'it will get the first worksheet (if any) in "REPORT" workbook (if open)
If TargetWS Is Nothing Then Exit Sub
''Location of Headers I want to search for in source file
Set TargetHeader = TargetWS.Range("A1:G1")
''Looping through all worksheets in source file, looking for the heading I want _
then copying that whole column to the target file I have
For Each ws In SourceWB.Sheets
For Each cell In ws.Rows(SourceHeaderRow).SpecialCells(xlCellTypeConstants, xlTextValues)
Set SourceCell = TargetHeader.Find(cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not SourceCell Is Nothing Then
Range(cell.Offset(1), ws.Cells(ws.Rows.Count, cell.Column).End(xlUp)).Copy
SourceCell.Offset(1).PasteSpecial xlPasteValues
End If
Next
Next
End Sub
Function GetWb(wbName As String) As Workbook
On Error Resume Next
Set GetWb = Workbooks(wbName)
On Error GoTo 0
If GetWb Is Nothing Then MsgBox "Sorry, the workbook '" & wbName & "' isn't open" & vbCrLf & vbCrLf & "Please open it and run the macro again"
End Function
Function GetWs(wbName As String, Optional wsName As Variant) As Worksheet
Dim wb As Workbook
Dim ws As Worksheet
Set wb = GetWb(wbName)
If wb Is Nothing Then Exit Function
On Error Resume Next
If IsMissing(wsName) Then
Set GetWs = wb.Worksheets(1) ' if no ws name passed then get the first one
Else
Set GetWs = wb.Worksheets(wsName)
End If
On Error GoTo 0
If GetWs Is Nothing Then MsgBox "Sorry, the worksheet '" & wsName & "0 isn't in '" & wb.Name & "'" & vbCrLf & vbCrLf & "Please open a valid workbook and run the macro again"
End Function