Add columns and lookup values in two different workbooks - excel
I have three workbooks, Workbook A, Workbook B and Workbook C.
To Workbook A, I want to add two columns at the end and call them "Item code" and "store code". The existing fields in Workbook A are "Item Descr" and "Store Descr".
To populate the field "Item code", I have to perform a lookup against Workbook B which has the columns "Item code" and "Item Descr".
To populate the "store code" column in Workbook A, I have to perform a lookup against Workbook C which has the columns "store code"and "store Descr".
This is my code so far:
Sub Macro1()
Dim LastRow As Long
Dim LastCol As Long
Dim iRow As Long
Set ws = Sheet1 ' NOTE: Change this if your data is not in Sheet1.
With ws
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
.Cells(1, LastCol + 1).Value = "Brand_item"
.Cells(1, LastCol + 2).Value = "Brand_code"
End With
Range("A2").Select
Selection.End(xlToRight).Select
Range("G2").Select
Windows("PE CLOSING OCT R2trial.xls").Activate
ActiveCell.FormulaR1C1 = _
"=INDEX([PEcodez.xlsx]Sheet1!R1C2:R2338C2,MATCH(RC[-3],
[PEcodez.xlsx]Sheet1!R1C1:R2338C1,0))"
Range("G2").Select
Selection.AutoFill Destination:=Range("G2:G2110")
Range("G2:G2110").Select
Range("G2").Select
Selection.Copy
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Range("G2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("H2").Select
Application.CutCopyMode = False
Windows("PE CLOSING OCT R2trial.xls").Activate
ActiveCell.FormulaR1C1 = _
"=INDEX([PEdoorcodes.xlsx]Sheet1!R1C3:R29C3,MATCH(RC[-7],[PEdoorcodes.xlsx]Sheet1!R1C1:R29C1,0))"
Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H2110")
Range("H2:H2110").Select
Range("H2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Range("H2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("H2").Select
Application.CutCopyMode = False
End Sub
How do I include the file path of the workbooks?
Update, I tried the following code to update my path:
ActiveCell.FormulaR1C1 = _
"=INDEX(C:\Users\amy\Documents\amyTrial\[PEcodez.xlsx]Sheet1!$A:$A,MATCH(RC[-3],C:\Users\amy\Documents\amy\[PEcodez.xlsx]Sheet1!R1C1:R2338C1,0))"
It gives me
Application-defined or object-defined error.
I have created some dummy workbooks/data on my end, as you did not provide screenshots.
For me, this is "Sheet1" in workbook A,
this is "Sheet1" in workbook B.
and this is "Sheet1" in workbook C.
I use the code below to look up item descriptions and store descriptions. You will need to change the file paths to workbook B and C in the code itself (provided you place the code itself in workbook A and run it from there).
Option Explicit
Private Sub lookupDescriptions()
Dim pathToWorkbookB As String
pathToWorkbookB = "C:\Users\User\Desktop\New folder\3 workbooks\B.xlsx" ' Change this to the real file path.
Dim pathToWorkbookC As String
pathToWorkbookC = "C:\Users\User\Desktop\New folder\3 workbooks\C.xlsx" ' Change this to the real file path.
Dim workbookB As Workbook ' Contains: Item code, item descr
Set workbookB = OpenWorkbook(pathToWorkbookB)
If workbookB Is Nothing Then
MsgBox ("Could not locate workbook B at the path below" & vbNewLine & vbNewLine & pathToWorkbookB & vbNewLine & vbNewLine & "Check file path provided. Code will stop running now.")
Exit Sub
End If
Dim workbookC As Workbook ' Contains: Store code, store descr
Set workbookC = OpenWorkbook(pathToWorkbookC)
If workbookC Is Nothing Then
MsgBox ("Could not locate workbook C at the path below" & vbNewLine & vbNewLine & pathToWorkbookC & vbNewLine & vbNewLine & "Check file path provided. Code will stop running now.")
Exit Sub
End If
' Workbooks A and B both contain "Item code",
' Get "Item description" from workbook B for each match
With ThisWorkbook.Worksheets("Sheet1")
Dim itemCodesInA As Range
Set itemCodesInA = .Range("A2:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
Dim storeCodesInA As Range
Set storeCodesInA = .Range("B2:B" & .Cells(.Rows.Count, 1).End(xlUp).Row)
End With
With workbookB.Worksheets("Sheet1")
Dim itemCodesInB As Range
Set itemCodesInB = .Range("A2:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
Dim itemDescriptionsInB As Range
Set itemDescriptionsInB = .Range("B2:B" & .Cells(.Rows.Count, 1).End(xlUp).Row)
End With
' Workbooks A and C both contain "Store code",
' Get "Store description" from workbook C for each match
With workbookC.Worksheets("Sheet1")
Dim storeCodesInC As Range
Set storeCodesInC = .Range("A2:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
Dim storeDescriptionsInC As Range
Set storeDescriptionsInC = .Range("B2:B" & .Cells(.Rows.Count, 1).End(xlUp).Row)
End With
' This is workbook A, change sheet name if necessary
With ThisWorkbook.Worksheets("Sheet1")
Dim lastRow As Long
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Dim lastColumn As Long
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
.Cells(1, lastColumn + 1).Value2 = "Item description"
With .Range(.Cells(2, lastColumn + 1), .Cells(lastRow, lastColumn + 1))
.Formula = "=INDEX(" & itemDescriptionsInB.Address(True, True, xlA1, True) & ",MATCH(" & itemCodesInA(1).Address(False, True, xlA1, False) & "," & itemCodesInB.Address(True, True, xlA1, True) & ",0))"
.Value2 = .Value2 ' Comment/delete this line to keep formulas
End With
.Cells(1, lastColumn + 2).Value2 = "Store description"
With .Range(.Cells(2, lastColumn + 2), .Cells(lastRow, lastColumn + 2))
.Formula = "=INDEX(" & storeDescriptionsInC.Address(True, True, xlA1, True) & ",MATCH(" & storeCodesInA(1).Address(False, True, xlA1, False) & "," & storeCodesInC.Address(True, True, xlA1, True) & ",0))"
.Value2 = .Value2 ' Comment/delete this line to keep formulas
End With
End With
' Close workbooks without saving
If Not (workbookB Is Nothing) Then workbookB.Close False
If Not (workbookC Is Nothing) Then workbookC.Close False
End Sub
Private Function OpenWorkbook(ByVal fullPathToWorkbook As String) As Workbook
If Len(Dir$(fullPathToWorkbook, vbNormal)) = 0 Then
Exit Function
End If
Dim workbookName As String
workbookName = VBA.Strings.Mid$(fullPathToWorkbook, VBA.Strings.InStrRev(fullPathToWorkbook, "\", -1, vbBinaryCompare) + 1)
Dim outputWorkbook As Workbook
On Error Resume Next
Set outputWorkbook = Application.Workbooks(workbookName)
On Error GoTo 0
If outputWorkbook Is Nothing Then
Set outputWorkbook = Application.Workbooks.Open(fullPathToWorkbook)
End If
Set OpenWorkbook = outputWorkbook
End Function
What I get in workbook A (after running the code above) is:
Owing to the differences between your workbooks and mine, it is unlikely that the code will work for you as is. You will likely need to change/tweak the code in certain places, if:
your sheets in workbook A, B, C are named something other than "Sheet1"
your data (including headers) has a different location/structure/layout
there are blanks/missing items (that would cause the lookup to fail)
Nonetheless, the code and accompanying screenshots may give you an idea on how to do it.
Related
To add the excel formulas into VBA Macro with condition
I have recorded some formulas into Macros and they are functioning properly, however I am not able to update them so that they should select the range themselves where the data ends in the last end in Column C. These 3 formulas extracts Date, File Name and Status of Files from Column A. As you see for now the range is e.g. "F3 to F313" where next time if the Data in Column C is up to C500 Range than I have to manually copy and paste the formulas. Is there anyway these 3 formulas should automatically detect the last text cell from Column C and ends there. That would be much helpful. To Extract Date Sub Macro13() 'To Extract Date ActiveCell.FormulaR1C1 = "=extractDate(RC[-1])" Range("D2").Select Selection.Copy Range("D3:D313").Select ActiveSheet.Paste Application.CutCopyMode = False End Sub To Find Status of File Sub Macro15() 'To Find Status of File ActiveCell.FormulaR1C1 = _ "=IFERROR(LOOKUP(2^15,SEARCH({""Feed"",""Feed 1"",""Feed 2""},RC[-3]),{""Feed"",""Feed 1"",""Feed 2""}),""Combine"")" Range("F2").Select Selection.Copy Range("F3:F313").Select ActiveSheet.Paste Application.CutCopyMode = False End Sub To extract File Name Sub Macro17() 'To extract File Name ActiveCell.FormulaR1C1 = _ "=IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABCD - GAMA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ALPHA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9," & _ "0},RC[-2]&""1234567890""))-1))=""ABCD - BETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""DBETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""A"",LEFT(RC[-2]," & _ "MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))="""",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABETA"",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),LEF" & _ "T(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2] & ""1234567890""))-1))))))))" Range("E2").Select Selection.Copy Range("E3:E313").Select ActiveSheet.Paste Application.CutCopyMode = False End Sub
Try this: Sub TestThis() Dim LastRow As Long, ws As Worksheet Set ws = ActiveSheet LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ws.Range("D2:D" & LastRow).FormulaR1C1 = "=extractDate(RC[-1])" ws.Range("F2:F" & LastRow).FormulaR1C1 = "=IFERROR(LOOKUP(2^15,SEARCH({""Feed"",""Feed 1"",""Feed 2""},RC[-3]),{""Feed"",""Feed 1"",""Feed 2""}),""Combine"")" ws.Range("E2:E" & LastRow).FormulaR1C1 = _ "=IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABCD - GAMA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ALPHA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+2),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9," & _ "0},RC[-2]&""1234567890""))-1))=""ABCD - BETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""DBETA "",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""A"",LEFT(RC[-2]," & _ "MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))="""",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+8),IF((LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))-1))=""ABETA"",LEFT(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2]&""1234567890""))+6),LEF" & _ "T(RC[-2],MIN(FIND({1,2,3,4,5,6,7,8,9,0},RC[-2] & ""1234567890""))-1))))))))" End Sub
Add a workbook once and paste the data in the same workbook on subsequent runs
I have a worksheet (sheet2) which contains a vlookup function with changing values in certain cells to refresh data. I want to copy any changed values to another workbook. Sub Copy_file() Dim xWs As Worksheet Dim Rng As Range Set Rng = Range("C6:M124") Application.Workbooks.Add Set xWs = Application.ActiveSheet Rng.Copy xWs.Cells(2, 2).PasteSpecial Paste:=xlPasteValues xWs.Cells(2, 2).PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False xWs.Cells(2, 2).PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False xWs.Cells(2, 2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats End Sub Every time the code runs it creates a new workbook. I need to modify it so that I can add a new workbook with a specific name and the copied data is pasted in sheet1 only when the macro runs for the first time. On subsequent runs the copied data should be pasted in the next sheet (e.g. Sheet2, Sheet3, Sheet4,... etc.) in the single workbook.
Please, try the next code: Sub Copy_file() Dim xWs As Worksheet, Rng As Range, wb As Workbook, wsMark As Worksheet Dim wbFullName As String, wbName As String, lastR As Long wbName = "MyWorkbook.xlsx" wbFullName = ThisWorkbook.Path & "\" & wbName Set Rng = Range("C6:M124") 'the range is set in the active workbook 'if the one keeping the code, please state it 'and the range will be fully qualified If dir(wbName) = "" Then 'if the necessary workbook does not exist Set wb = Application.Workbooks.Add 'create it wb.saveas wbName 'name the newly created workbook Set wsMark = wb.Sheets(wb.Sheets.count) wsMark.Name = "UsedSheets" 'name the last sheet keeping copying order End If If wb Is Nothing Then 'if not created above, but exists: On Error Resume Next Set wb = Workbooks(wbName) 'check if it is open Set wsMark = wb.Worksheets("UsedSheets") 'set the sheet keeping copying order On Error GoTo 0 End If 'if not open, open it: If wb Is Nothing Then Set wb = Workbooks.Open(wbFullName) Set wsMark = wb.Worksheets("UsedSheets") 'set the sheet keeping copying order End If lastR = wsMark.Range("A" & wsMark.rows.count).End(xlUp).row 'last used row in the sheet If lastR > 1 Then If CLng(wsMark.Range("A" & lastR).value) < (wb.Sheets.count - 2) Then Set xWs = wb.Sheets(CLng(wsMark.Range("A" & lastR).value + 1)) wsMark.Range("A" & lastR + 1).value = xWs.Index Else Set xWs = wb.Sheets.Add(Before:=wsMark) wsMark.Range("A" & lastR + 1).value = xWs.Index End If Else Set xWs = wb.Sheets(1): wsMark.Range("A" & lastR + 1).value = 1 End If Rng.copy With xWs.cells(2, 2) .PasteSpecial Paste:=xlPasteValues .PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteValuesAndNumberFormats End With End Sub Edited: Please, test the next variant. It open a new workbook, first time you run the code and uses it until you close it. You must manually save it, when finished the copying process... Sub Copy_file() Dim xWs As Worksheet, Rng As Range, wb As Workbook, wsMark As Worksheet Dim wbFullName As String, wbName As String, lastR As Long wbName = "MyWorkbook.xlsx" wbFullName = ThisWorkbook.Path & "\" & wbName Set Rng = Range("C6:M124") If dir(wbName) = "" Then 'if the necessary workbook does not exist Set wb = Application.Workbooks.Add 'create it wb.saveas wbName 'name the newly created workbook Set wsMark = wb.Sheets(wb.Sheets.count) wsMark.Name = "UsedSheets" 'name the last sheet keeping copying order End If If wb Is Nothing Then 'if not created above, but exists: On Error Resume Next Set wb = Workbooks(wbName) 'check if it is open Set wsMark = wb.Worksheets("UsedSheets") 'set the sheet keeping copying order On Error GoTo 0 End If 'if not open, open it: If wb Is Nothing Then Set wb = Workbooks.Open(wbFullName) Set wsMark = wb.Worksheets("UsedSheets") 'set the sheet keeping copying order End If lastR = wsMark.Range("A" & wsMark.rows.count).End(xlUp).row 'last used row in the sheet If lastR > 1 Then If CLng(wsMark.Range("A" & lastR).value) < wb.Sheets.count - 1 Then Set xWs = wb.Sheets(CLng(wsMark.Range("A" & lastR).value + 1)) wsMark.Range("A" & lastR + 1).value = xWs.Index Else Set xWs = wb.Sheets.Add(Before:=wsMark) wsMark.Range("A" & lastR + 1).value = xWs.Index End If Else Set xWs = wb.Sheets(1): wsMark.Range("A" & lastR + 1).value = 1 End If Rng.copy With xWs.cells(2, 2) .PasteSpecial Paste:=xlPasteValues .PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteValuesAndNumberFormats End With End Sub Sub Copy_file1() Dim xWs As Worksheet, Rng As Range, wb As Workbook Dim w As Workbook, wsMark As Worksheet, lastR As Long Set Rng = Range("C6:M124") 'if active sheet belongs to the workbook keeping this code 'it should be adapted to fully qualify the range If wb Is Nothing Then 'check if wb exists but it losts the reference because of an error: For Each w In Workbooks 'iterate between open workbooks: If w.Sheets(w.Sheets.count).Name = "UsedSheets" Then Set wb = w Set wsMark = wb.Worksheets("UsedSheets"): Exit For End If Next w End If 'if wb does not exist: If wb Is Nothing Then Set wb = Application.Workbooks.Add 'open a new workbook and set it Set wsMark = wb.Sheets(wb.Sheets.count) 'set the last sheet like the one to keep copying order wsMark.Name = "UsedSheets" End If If left(Rng.Parent.Parent.Name, 4) = "Book" Then 'if, by mistake, the selection is done on a wb sheet: MsgBox "The active sheet where ""Rng"" was set belongs to the workbook where to copy..." & vbCrLf & _ "It should be a mistake. Please, select the appropriate sheet!", vbInformation, "Wrong sheet selected.." Exit Sub End If lastR = wsMark.Range("A" & wsMark.rows.count).End(xlUp).row 'last used row in the sheet If lastR > 1 Then 'for the first time (when wb has been created): If CLng(wsMark.Range("A" & lastR).value) < wb.Sheets.count - 1 Then Set xWs = wb.Sheets(CLng(wsMark.Range("A" & lastR).value + 1)) wsMark.Range("A" & lastR + 1).value = xWs.Index Else 'if is not the first copying time: Set xWs = wb.Sheets.Add(Before:=wsMark) wsMark.Range("A" & lastR + 1).value = xWs.Index End If Else Set xWs = wb.Sheets(1): wsMark.Range("A" & lastR + 1).value = 1 End If Rng.copy With xWs.cells(2, 2) .PasteSpecial Paste:=xlPasteValues .PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteValuesAndNumberFormats End With End Sub
Try: Sub Copy_file() Application.ScreenUpdating = False Dim xWs As Worksheet Static WB As Workbook ' static variables stores its values between proc calls If WB Is Nothing Then ' check if a certain workbook exists. if no, create it Set WB = Workbooks.Add Else WB.Worksheets.Add after:=WB.Sheets(WB.Sheets.Count) ' create the next WS End If Set xWs = ActiveSheet ThisWorkbook.Sheets("Sheet2").Range("C6:M124").Copy With xWs.Cells(2, 2) .PasteSpecial Paste:=xlPasteValues .PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False .PasteSpecial Paste:=xlPasteValuesAndNumberFormats End With Application.ScreenUpdating = True End Sub
Compiler error 'Next without For' - can't understand why
This is a simple For ... Next so why am I getting the error, is it related to the function somehow? The macro I supposed to find a specific worksheet within a large workbook, get some data and copy it to a separate workbook named after the worksheet. Most of this came from mw recording a macro with changes were necessary. Dim wbThisWB As Workbook Dim LastRow As Long Dim WSName As String Dim lRow As Long Workbooks.Open Filename:= _ "\\Shenetapp01\itt viability and intervention\Assurance Work AY 17-18\AGR\Test\16-17 EY Trainees test.xls" LastRow = wbThisWB.Worksheets("Sheet1").Cells(Row.Count, 1).End(xlUp).Row For I = 1 To LastRow WSName = wbThisWB.Worksheets("Sheets1").Cells(I, 1) If sheetExists(WSName, wbThisWB) Then MsgBox "Sheet found:" & WSName lRow = Cells(Rows.Count, 1).End(xlUp).Row ActiveSheet.Range("C2", "M" & lRow).Copy Workbooks.Open Filename:="\\Shenetapp01\itt viability and intervention\Assurance Work AY 17-18\AGR\Test\" & WSName & " 17-18 AGR.xlsx" Sheets("EY 17-18 Starters").Select Range("C6").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False ActiveWorkbook.Save ActiveWindow.Close Next I End Sub Function sheetExists(sheetToFinad As String, wbThisWB As Workbook) As Boolean sheetExists = False For Each Sheet In wbThisWB.Worksheets If sheetToFind = Sheet.Name Then sheetExists = True Exit Function End If Next Sheet End Function
Copy column of filtered cells and paste to different column
I am currently working on a code to copy the filtered results of column CJ and paste them in column F. When I attempt to paste it is only pasting in the unfiltered areas and is removing the rest of the column's cells. Any idea of the correct code? With ActiveSheet With Intersect(.Range("CJ:CJ"), .UsedRange) .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Copy End With End With ActiveSheet.Range("F1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, _Operation:=xlNone, SkipBlanks:=False, Transpose:=False Thanks!
for i = 1 to ActiveSheet.Range("C" & Rows.Count).End(xlUp).Row If Range("C" & i).entireRow.hidden = False then Range("F" & i).value = Range("C" & i).value Next i
Here is a sample code I found that satisfies the filtered copy & paste. Thanks! Sub CopyPasteFormula() Dim Ws As Worksheet Dim LRow As Long Dim PasteRng As Range Set Ws = Worksheets("Sheet1") LRow = Ws.Range("K" & Rows.Count).End(xlUp).Row Set PasteRng = Ws.Range("H1:H" & LRow).SpecialCells(xlCellTypeVisible) Ws.Range("K:K").SpecialCells(xlCellTypeVisible).Copy PasteRng.PasteSpecial xlPasteFormulas Application.CutCopyMode = False End Sub
Setting excel VBA Range from multiple variables
I'm having trouble with the Range function. (Nearly) completed code below. I'm fairly new to VBA, so please explain the basics if you have the time. This is the line that is giving me a debug error: Set CombinedPropRange = ThisWorkbook.Worksheets("PropFiltered").Range("A" & _ PropACount & ":J" & SplitTabName(2)) Full Code Below: Sub FillTabsTest() ' FillTabsTest Macro HowManyTabsDoYouNeed = 4 'If you want to add or remove Tabs, you must change this number AND add/subtract from the "TabName(1)" section below. ReDim TabName(1 To HowManyTabsDoYouNeed) As String 'Grabs Data from Original Workbook and creates a new Workbook. Range("A1").Select Range(Selection, Selection.End(xlToRight)).Select Range("A1:P1").Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Workbooks.Add ActiveSheet.Paste Call WrapText TabName(1) = "April H.,0,1000" TabName(2) = "Christopher H.,0,1000" TabName(3) = "Christie E.,500,500" TabName(4) = "Cori M.,500,500" 'Places Filtered Auto Events on its own tab Sheets("Sheet1").Select Cells.Select Selection.AutoFilter ActiveSheet.Range("$A:$S").AutoFilter Field:=8, Criteria1:="=COMAUTO", _ Operator:=xlOr, Criteria2:="=PERSAUTO" ActiveSheet.Range("$A:$S").AutoFilter Field:=5, Criteria1:="=3*", Operator _ :=xlAnd ActiveSheet.Range("$A:$S").AutoFilter Field:=9, Criteria1:=Array( _ "AUTO BODILY INJURY", "AUTO MED PAY", "AUTO PROPERTY DAMAGE", "AUTO-ENDORSEMENT", _ "AUTO-OTHER", "BODILY INJURY", "COLLISION", "COMPREHENSIVE", "LIABILITY", "OTHER", _ "RENTAL REIMBURSEMENT", "UM/UIM"), Operator:=xlFilterValues Selection.SpecialCells(xlCellTypeVisible).Select Selection.Copy Sheets.Add After:=Sheets(Sheets.Count) ActiveSheet.Name = "AutoFiltered" ActiveSheet.Paste 'Places Filtered Property Events on its own tab Sheets("Sheet1").Select Cells.Select Application.CutCopyMode = False ActiveSheet.ShowAllData Cells.Select ActiveSheet.Range("$A:$S").AutoFilter Field:=8, Criteria1:="=COMPROP", _ Operator:=xlOr, Criteria2:="=PLPROP" ActiveSheet.Range("$A:$S").AutoFilter Field:=5, Criteria1:="=3*", Operator _ :=xlAnd ActiveSheet.Range("$A:$S").AutoFilter Field:=12, Criteria1:="<>*FIRE*", _ Operator:=xlOr, Criteria2:="<>*SMOKE*" Selection.SpecialCells(xlCellTypeVisible).Select Selection.Copy Sheets.Add After:=Sheets(Sheets.Count) ActiveSheet.Name = "PropFiltered" ActiveSheet.Paste 'Begin adding the above named tabs to the workbook For i = 1 To HowManyTabsDoYouNeed Sheets.Add After:=Sheets(Sheets.Count) SplitTabName = Split(TabName(i), ",") ActiveSheet.Name = SplitTabName(0) Next i 'Begin populating employee's sheets. Dim AutoACount As Integer Dim PropACount As Integer ' Dim AutoAPasteCount As Integer Dim PropAPasteCount As Integer Dim AutoJCount As Integer Dim PropJCount As Integer 'Dim AutoRangeA As Range 'Dim AutoRangeJ As Range 'Dim PropRangeA As Range 'Dim PropRangeJ As Range Dim PropAPasteCountRange As String Dim CombinedPropRange As Range Dim CombinedAutoRange As Range AutoACount = 2 PropACount = 2 AutoJCount = 2 PropJCount = 2 PropAPasteCount = 2 For i = 1 To HowManyTabsDoYouNeed SplitTabName = Split(TabName(i), ",") If SplitTabName(1) <> "0" Then ' Set AutoRangeA = Range("A" & AutoACount) ' Set AutoRangeJ = Range("J" & SplitTabName(1)) Sheets("AutoFiltered").Select Set CombinedAutoRange = ThisWorkbook.Worksheets("AutoFiltered").Range("A" & AutoACount & ":J" & SplitTabName(1)) CombinedAutoRange.Copy Sheets("SplitTabName(0)").Select ActiveSheet.Paste AutoACount = AutoACount + SplitTabName(1) PropAPasteCount = SplitTabName(1) End If If SplitTabName(2) <> "0" Then 'Set PropRangeA = Range("A" & PropACount) 'MsgBox PropRangeA 'Set PropRangeJ = Range("J" & SplitTabName(2)) PropAPasteCountRange = "A" & PropAPasteCount 'Sheets("PropFiltered").Select Set CombinedPropRange = ThisWorkbook.Worksheets ("PropFiltered").Range("A" & PropACount & ":J" & SplitTabName(2)) CombinedPropRange.Copy Sheets("SplitTabName(0)").Select ThisWorkbook.Worksheets(SplitTabName(0)).Cells(PropAPasteCountRange).Select ActiveSheet.Paste PropACount = PropACount + SplitTabName(2) End If Next i End