I am a beginner in VBA and I am trying to fix an issue in a code written by someone else. Any help will be much appreciated.
Background:
The main macro workbook uses reference data from other excel files. The file path for the reference files are referenced within the main macro workbook in "reference workbooks" tab. They are loaded as Arrays in the macro workbook. For one of the reference data files, I need to sort and filter the data in a particular sheet, then copy all the cells still visible into a sheet in the main macro workbook.
Issue:
Currently the macro only copies and pastes the header rows and 42 blank rows. There are more than 1000 rows with data which are not copied. The data in reference files is normally between columns A:BL.
I've shared only the relevant portion of the code for this problem - there are multiple reference files otherwise.
Sub dataLoad()
Dim wb As Workbook: Set wb = ThisWorkbook
refpath = wb.path & "\Reference Files\"
path = ThisWorkbook.path
Set refiles = Sheets("Reference Workbooks")
SourceData = refiles.Range("B13").Value
wrksht'SourceData = refiles.Range("C13").Value
'1) COPY REFERENCE WORKSHEETS TO WORKBOOK:
'This allows the template to access the reference materials without having to open and close external documents
'1a)Create arrays for the reference workbooks
Dim fileArr() As Variant
ReDim fileArr(5)
fileArr = Array(SourceData)
'1b)Create arrays for the reference worksheets
Dim wrkshtArr() As Variant
ReDim wrkshtArr(5)
wrkshtArr = Array(wrkshtSourceData)
Dim intcount As Integer
Dim intsheet As Integer
Dim sheetArr() As Variant
intsheet = ActiveWorkbook.Sheets.Count
ReDim sheetArr(intsheet)
For intcount = 1 To intsheet
sheetArr(intcount) = ActiveWorkbook.Sheets(intcount).Name
Next
'1c)A For statement that(i) checks if reference worksheet is already loaded and (ii) copies them to the workbook if not
Application.ScreenUpdating = False
For i = 0 To UBound(fileArr)
testvar = False
For x = 0 To UBound(sheetArr)
If testvar = False Then
If sheetArr(x) = wrkshtArr(i) Then
testvar = True
End If
End If
Next x
If testvar = False Then
Set closedBook = Workbooks.Open(refpath & fileArr(i))
closedBook.Sheets(wrkshtArr(i)).Copy After:=Workbooks(wb.Name).Sheets(wb.Worksheets.Count)
closedBook.Close SaveChanges:=False
Worksheets(wrkshtArr(i)).Visible = xlSheetHidden
End If
Next i
With Worksheets(wrkshtSourceData)
Dim Datadate As Range: Set Datadate = .Rows("1:1").Find(What:="Date_of_Entry", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
Dim Datastatus As Range: Set Datastatus = .Rows("1:1").Find(What:="FinalStatus", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
.Activate
.UsedRange.Sort Key1:=Range(.Columns(Datadate.Column).Address(Rowabsolute:=False)), Order1:=xlDescending, Header:=xlYes
.Range(.Columns(Datastatus.Column).Address(Rowabsolute:=False)).AutoFilter Field:=1, Criteria1:="Approved"
Sheets.Add.Name = "Database2"
.UsedRange.SpecialCells(xlCellTypeVisible).Copy
Worksheets("Database2").Paste
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
Worksheets("Database2").Name = wrkshtSourceData
Worksheets(wrkshtSourceData).Visible = xlSheetHidden
End With
Application.ScreenUpdating = True
End Sub
Maybe you can set the range you need using coordinates of the complete shown data. My contributions inside '#####code lines
Please let my know if you need some edit, to this answer, because I'm not sure of this.
Sub dataLoad()
Dim wb As Workbook: Set wb = ThisWorkbook
refpath = wb.Path & "\Reference Files\"
Path = ThisWorkbook.Path
Set refiles = Sheets("Reference Workbooks")
SourceData = refiles.Range("B13").Value
wrksht 'SourceData = refiles.Range("C13").Value
'1) COPY REFERENCE WORKSHEETS TO WORKBOOK:
'This allows the template to access the reference materials without having to open and close external documents
'1a)Create arrays for the reference workbooks
Dim fileArr() As Variant
ReDim fileArr(5)
fileArr = Array(SourceData)
'1b)Create arrays for the reference worksheets
Dim wrkshtArr() As Variant
ReDim wrkshtArr(5)
wrkshtArr = Array(wrkshtSourceData)
Dim intcount As Integer
Dim intsheet As Integer
Dim sheetArr() As Variant
intsheet = ActiveWorkbook.Sheets.Count
ReDim sheetArr(intsheet)
For intcount = 1 To intsheet
sheetArr(intcount) = ActiveWorkbook.Sheets(intcount).Name
Next
'1c)A For statement that(i) checks if reference worksheet is already loaded and (ii) copies them to the workbook if not
Application.ScreenUpdating = False
For i = 0 To UBound(fileArr)
testvar = False
For x = 0 To UBound(sheetArr)
If testvar = False Then
If sheetArr(x) = wrkshtArr(i) Then
testvar = True
End If
End If
Next x
If testvar = False Then
Set closedBook = Workbooks.Open(refpath & fileArr(i))
closedBook.Sheets(wrkshtArr(i)).Copy After:=Workbooks(wb.Name).Sheets(wb.Worksheets.Count)
closedBook.Close SaveChanges:=False
Worksheets(wrkshtArr(i)).Visible = xlSheetHidden
End If
Next i
'#####################code
Dim R 'To get the last visible row
Dim C 'To get the last column
Dim L 'To get the size of the worksheet
With Worksheets(wrkshtSourceData)
Dim Datadate As Range: Set Datadate = .Rows("1:1").Find(What:="Date_of_Entry", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
Dim Datastatus As Range: Set Datastatus = .Rows("1:1").Find(What:="FinalStatus", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
.Activate
.UsedRange.Sort Key1:=Range(.Columns(Datadate.Column).Address(Rowabsolute:=False)), Order1:=xlDescending, Header:=xlYes
.Range(.Columns(Datastatus.Column).Address(Rowabsolute:=False)).AutoFilter Field:=1, Criteria1:="Approved"
Dim Sht As Worksheet: Set Sht = Sheets.Add 'Store the sheet into a var...
Sht.Name = "Database2"
L = Range("A1").EntireColumn.Rows.Count 'Set the value of L
R = Range(Cells(L, 1), Cells(L, 1)).End(xlUp).Row '... of R
C = Range("A1").End(xlToRight).Column '...and C
Dim OriginRange As Range: Set OriginRange = .Range(Cells(1, 1), Cells(R, C)).SpecialCells(xlCellTypeVisible)
'Here get the range of visible cells and store the range into the var
OriginRange.Copy
Sht.Activate
Sht.Range("A1").PasteSpecial (xlPasteAll)
Application.CutCopyMode = False
.Delete
Application.DisplayAlerts = True
Sht.Name = wrkshtSourceData
Worksheets(wrkshtSourceData).Visible = xlSheetHidden
End With
'#####################code
Application.ScreenUpdating = True
End Sub
I managed to find the answer to this through trial and error. It was simpler than I was making it out to be.
The person who wrote the code forgot to add Selection.AutoFilter in the last section of the code. Updated for your reference between ####.
Thanks a lot to anyone who attempted to resolve this/ posted the answer.
With Worksheets(wrkshtSourceData)
Dim Datadate As Range: Set Datadate = .Rows("1:1").Find(What:="Date_of_Entry", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
Dim Datastatus As Range: Set Datastatus = .Rows("1:1").Find(What:="FinalStatus", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
.Activate
####
Selection.AutoFilter
####
.UsedRange.Sort Key1:=Range(.Columns(Datadate.Column).Address(Rowabsolute:=False)), Order1:=xlDescending, Header:=xlYes
.Range(.Columns(Datastatus.Column).Address(Rowabsolute:=False)).AutoFilter Field:=1, Criteria1:="Approved"
Sheets.Add.Name = "Database2"
.UsedRange.SpecialCells(xlCellTypeVisible).Copy
Worksheets("Database2").Paste
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
Worksheets("Database2").Name = wrkshtSourceData
Worksheets(wrkshtSourceData).Visible = xlSheetHidden
End With
Application.ScreenUpdating = True
End Sub
Related
I would Like to only copy the information in Range A2:P13. This Data gets spit out In different rows from time to time, and some times additional data in some of the columns gets added. I wrote a script that allows me to Select and copy everything from the last row to an x number rows up. Problem is that this amount of rows can be variable And there is way more data above the shared image (its clutter). Is there a way to modify my script so it counts down to the last row and once it hits "n" or "Calibration" it selects 8 rows above it?
Thanks in advance :)
enter image description here
Option Explicit
Sub Import_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim myValue As Variant
Dim Sht2 As Worksheet
Dim lastRow As Long
Dim Last24Rows As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
myValue = InputBox("Please Input Run Number")
FileToOpen = Application.GetOpenFilename("Excel Files (*.xl*),*.xl*", , "Choose File", "Open", False)
If FileToOpen = False Then
Exit Sub
Else
Set OpenBook = Workbooks.Open(FileToOpen)
Set Sht2 = OpenBook.Sheets("Sheet1")
End If
lastRow = Sht2.Range("H" & Sht2.Rows.Count).End(xlUp).row
Set Last4Rows = Sht2.Range("A" & lastRow - 4 & ":AZ" & lastRow)
Last4Rows.Copy
ThisWorkbook.Worksheets(myValue).Range("A1").PasteSpecial xlPasteValues
OpenBook.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I tried Including this
' Dim wb As Workbook
' Dim ws As Worksheet
' Dim FoundCell As Range
' Set wb = ActiveWorkbook
' Set ws = ActiveSheet
'
' Const WHAT_TO_FIND As String = "Calibration"
'
' Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
' If Not FoundCell Is Nothing Then
' MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
' Else
' MsgBox (WHAT_TO_FIND & " not found")
' End If
But it did not work
This will select 8 rows above wherever it finds "calibration". The -8 makes it move up 8 rows, and then the resize(8) resizes it to include the 8 rows below. It will create an error if it can't find "calibration", it would be easy to change that to send a text box instead.
Sub Macro1()
'
' Macro1 Macro
'
'
Dim found As Range
Dim SelectionRange As Range
Dim what_to_find As String
Dim FoundRow As Long
what_to_find = "calibration"
Set found = Cells.Find(What:=what_to_find, After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
FoundRow = found.row
Set SelectionRange = Rows(FoundRow - 8).Resize(8)
SelectionRange.Select
End Sub
I am trying to copy data from a .xlsm to a .xlsx file in SharePoint (SP). My code does several other things for moving data but the issue I am having is getting the source row from 1 doc to another doc in SP.
I am hoping someone can assist.
Sub Complete()
Dim tb1 As ListObject, tb2 As ListObject
Dim Lrow As Long, dRow As Long
Dim ws As Worksheet, ws1 As Worksheet
Dim searchRange As Range, foundCell As Range
Dim mysearch As String
Dim wb As Workbook, Scwb As Workbook
Application.DisplayAlerts = False
Set wb = ThisWorkbook
Set ws = wb.Sheets("OI")
mysearch = ws.Range("D4").Value
Set tb1 = ws.ListObjects("OITs")
Set tb2 = wb.Sheets("TDets").ListObjects("OIFinal")
Lrow = tb2.ListRows.Count
With ws
.Range("A:A").EntireColumn.Hidden = False
End With
tb1.Range.AutoFilter Field:=11, Criteria1:="<>" & vbNullString
NumRows = tb1.DataBodyRange.Cells.SpecialCells(xlCellTypeVisible).Rows.Count
tb1.DataBodyRange.Cells.SpecialCells(xlCellTypeVisible).Copy
tb2.DataBodyRange(Lrow + 1, 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
tb1.DataBodyRange.Columns(4).Resize(, 7).ClearContents
tb1.Range.AutoFilter Field:=11, Criteria1:="=" & vbNullString
With ws
.Range("A:A").EntireColumn.Hidden = True
End With
With wb.Sheets("CRqs")
Set searchRange = .Range("G1", .Range("G" & .Rows.Count).End(xlUp))
End With
Set Scwb = Workbooks.Open("https://******.sharepoint.com/sites/******/Shared%20Documents/General/NAA.xlsx") 'Opens the doc that I am looking to paste the data in
Set dRow = Scwb.Sheets("AppAccs").Cells(Scwb.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Set foundCell = searchRange.Find(what:=mysearch, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not foundCell Is Nothing Then
foundCell.Offset(0, 6).Value = "Yes"
foundCell.Offset(0, -6).EntireRow.Copy _ 'this works copying the source row of data from a reference entered (mysearch)
dRow ' this now fails with a runtime error 1004
Else
MsgBox "We cannot find the ID " & mysearch & " to send. Please check ID."
End If
Application.DisplayAlerts = True
End Sub
If anyone can help or needs any further info please let me know. Thanks,
I was (reluctantly) nice to offer to help my HR department with creating a macro that will import an exported CSV from our accounting software to our existing Excel worksheet to track sales.
I thought I finally figured it out. But, now I'm getting subscript out of range errors when I import the data.
Does anyone see something I'm missing? Thank you.
Note: the staff barely knows how to use a computer, let alone excel. I'm not going to teach them how to use power query. I just wanted to have a nice button "update" they click on... select the file and done.
Dim FileToOpen As String
FileToOpen = GetFileName
If FileToOpen <> "" Then
Dim OpenBook As Workbook
Set OpenBook = Workbooks.Open(FileToOpen)
'Find last cell in CSV file.
Dim Source_LastCell As Range
Set Source_LastCell = LastCell(OpenBook.Worksheets(1))
'Find last cell in reporting workbook.
'ThisWorkbook means the file that the code is in.
Dim Target_LastCell As Range
Set Target_LastCell = LastCell(ThisWorkbook.Worksheets("Services Data")).Offset(1)
'Copy and paste - it's a CSV so won't contain formula, etc.
With OpenBook.Worksheets(1)
.Range(.Cells(2, 1), Source_LastCell).Copy _
Destination:=ThisWorkbook.Worksheets("Services Data").Cells(Target_LastCell.Row, 1)
End With
OpenBook.Close SaveChanges:=False
End If
End Sub
Public Function GetFileName() As String
Dim FD As FileDialog
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.InitialFileName = ThisWorkbook.Path & Application.PathSeparator
.AllowMultiSelect = False
If .Show = -1 Then
GetFileName = .SelectedItems(1)
End If
End With
Set FD = Nothing
End Function
Public Function LastCell(wrkSht As Worksheet) As Range
Dim lLastCol As Long, lLastRow As Long
On Error Resume Next
With wrkSht
lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
End With
If lLastCol = 0 Then lLastCol = 1
If lLastRow = 0 Then lLastRow = 1
Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
On Error GoTo 0
End Function
The Subscript out of range on the below line
Set Target_LastCell = LastCell(ThisWorkbook.Worksheets("Services Data")).Offset(1)
indicates that the code was not able to find the worksheet Services Data.
I would do this differently though. Does this help? I have commented the code so you should not have any difficulty to understand it. However, if you do, then simply ask.
Option Explicit
Dim NothingToCopy As Boolean
Sub Sample()
Dim wbCsv As Workbook
Dim wsThis As Worksheet, wsThat As Worksheet
Dim FileToOpen As Variant
Dim rngFromCopy As Range, rngToCopy As Range
'~~> Services Data worksheet
Set wsThis = ThisWorkbook.Sheets("Services Data")
'~~> Browse to csv file
FileToOpen = Application.GetOpenFilename("Csv Files (*.csv), *.csv")
If FileToOpen = False Then Exit Sub
'~~> Open the csv file
Set wbCsv = Workbooks.Open(FileToOpen)
'~~> Set the sheet from where to copy
Set wsThat = wbCsv.Sheets(1)
'~~> Identify the range to copy and paste
Set rngFromCopy = wsThat.Range(wsThat.Cells(2, 1), LastCell(wsThat))
'~~> If CSV is blank then there is nothing to copy
If NothingToCopy = True Then
MsgBox "There is no data to copy"
Else
'~~> Identify where to copy
Set rngToCopy = wsThis.Cells(LastCell(wsThis).Row + 1, 1)
'~~> Copy and paste
rngFromCopy.Copy rngToCopy
'~~> Give time to excel to do the copy and paste
DoEvents
End If
'~~> Close without saving
wbCsv.Close (False)
End Sub
'~~> Function to find last row and column
Private Function LastCell(wrkSht As Worksheet) As Range
Dim wsThatLRow As Long, wsThatLCol As Long
With wrkSht
'~~> Check if the worksheet as has data
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
'~~> Get last row and column
wsThatLRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
wsThatLCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
wsThatLRow = 1
wsThatLCol = 1
'~~> CSV has nothing to copy
NothingToCopy = True
End If
Set LastCell = .Cells(wsThatLRow, wsThatLCol)
End With
End Function
I have some tables from Excel that will be updated every month or so, what I am trying to do is to copy and paste those ranges from a "master workbook" to some several sheets. The way this works is I have 20 plus workbooks with those ranges "tables" already there, but I am having to manually open those workbooks then copy and paste the new values from the master workbook and close it.
Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant
Dim ws As Worksheet
Dim rngCopy As Range, aCell As Range, bcell As Range
Dim strSearch As String
Dim StrFile As Variant
Dim wb2 As Excel.Workbook
Application.DisplayAlerts = True
Application.ScreenUpdating = True
StrFile = Dir("C:\temp\*.xlsx*")
Do While Len(StrFile) > 0
Set wb = Workbooks.Open(StrFile)
'NewFile = Application.GetOpenFilename("microsoft excel files (*.xl*), *.xl*")
'
'If NewFile <> False Then
'Set wkbk = Workbooks.Open(NewFile)
'''**********************
strSearch = "Descitption"
Set ws = Worksheets("TestCases")
With ws
Set aCell = .Columns(4).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Set bcell = aCell
If rngCopy Is Nothing Then
Set rngCopy = .Rows((aCell.Row + 1) & ":" & (aCell.Row + 2))
Else
Set rngCopy = Union(rngCopy, .Rows((aCell.Row + 1) & ":" & (aCell.Row + 2)))
End If
Do
Set aCell = .Columns(4).FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bcell.Address Then Exit Do
If rngCopy Is Nothing Then
Set rngCopy = .Rows((aCell.Row + 1) & ":" & (aCell.Row + 2))
Else
Set rngCopy = Union(rngCopy, .Rows((aCell.Row + 1) & ":" & (aCell.Row + 2)))
End If
Else
Exit Do
End If
Loop
Else
MsgBox SearchString & " not Found"
End If
'~~> I am pasting to Output sheet. Change as applicable
Set wb2 = Workbooks.Open("C:\temp\Bulk tool\test1.xlsm")
If Not rngCopy Is Nothing Then rngCopy.Copy 'paste to another worksheet Sheets("Output").Rows(1)
End With
'**************************
ActiveWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
StrFile = Dir
Loop
End Sub
The range is dynamic, it can change from 2 rows to 20, but to give an example A1:K20 and it will go to the same range to another workbook.
first off let me thank everyone helping me on this.
here is what I have so far (see code)
when I run it I am getting error 1004 not sure what I changed but it was working fine, also what I am trying to do, is to copy to another worksheet.
Copying and pasting values in a worksheet uses the Range.Copy and Range.PasteSpecial.
An example code is as follows:
Sub CopyThis()
Dim Sht1 As Worksheet, Sht2 As Worksheet
Set Sht1 = ThisWorkbook.Sheets(1)
Set Sht2 = ThisWorkbook.Sheets(2)
Sht1.Range("A1:D4").Copy
Sht2.Range("A1:D4").PasteSpecial xlPasteAll
End Sub
Alternatively, you can also loop through values. I usually do this out of preference because I often do "If Then" in loops
Sub CopyThis2()
Dim Sht1 As Worksheet, Sht2 As Worksheet
Set Sht1 = ThisWorkbook.Sheets(1)
Set Sht2 = ThisWorkbook.Sheets(2)
Dim i As Long, j As Long
For i = 1 To 4
For j = 1 To 4
Sht2.Cells(i, j).Value = Sht1.Cells(i, j).Value
Next j
Next i
End Sub
Perhaps you can do little tricks with coding to make it faster. Like in this Answer below
Looping through files in a Folder
You can Also use Application.Screenupdating = False before the loop & True after the loop, so that your process would be way faster. In the Loop you can put the Code suggested by Parker.R ....
Also, there is no other way to copy data from workbooks without opening them in VBA.All you can do it play with the way files are being opened and closed so that the process becomes faster.
Other than Screenupdating few more properties you can Set As per this Link
Code to loop Using FSO
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim objFSO As Object
Dim objFolder, sfol As Object
Dim objFile As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.getFolder(f_add) ''''f_add is the Address of the folder
'''' Loop For Files in That Folder
For Each objFile In objFolder.Files
''''Your Code
Next
'''' Loop for All the Subfolders in The Folder
For Each sfol In objFolder.subfolders
''' Your Code Here
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
I have checked a bunch of different posts and can't seem to find the exact code I am looking for. Also I have never used VBA before so I'm trying to take codes from other posts and input my info for it to work. No luck yet. At work we have a payroll system in Excel. I am trying to search for my name "Clarke, Matthew" and then copy that row and paste it to the workbook I have saved on my desktop "Total hours".
CODE
Sub Sample()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long '<~~ Not Integer. Might give you error in higher versions of excel
Dim strSearch As String
Set wb1 = ThisWorkbook
Set ws1 = wb1.Worksheets("yourSheetName")
strSearch = "Clarke, Matthew"
With ws1
'~~> Remove any filters
.AutoFilterMode = False
'~~> I am assuming that the names are in Col A
'~~> if not then change A below to whatever column letter
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
With .Range("A1:A" & lRow)
.AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"
Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
End With
'~~> Remove any filters
.AutoFilterMode = False
End With
'~~> Destination File
Set wb2 = Application.Workbooks.Open("C:\Sample.xlsx")
Set ws2 = wb2.Worksheets("Sheet1")
With ws2
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lRow = 1
End If
copyFrom.Copy .Rows(lRow)
End With
wb2.Save
wb2.Close
End Sub
SNAPSHOT
Expanding on what timrau said in his comment, you can use the AutoFilter function to find the row with your name in it. (Note that I'm assuming you have the source workbook open)
Dim curBook As Workbook
Dim targetBook As Workbook
Dim curSheet As Worksheet
Dim targetSheet As Worksheet
Dim lastRow As Integer
Set curBook = ActiveWorkbook
Set curSheet = curBook.Worksheets("yourSheetName")
'change the Field number to the correct column
curSheet.Cells.AutoFilter Field:=1, Criteria1:="Clarke, Matthew"
'The Offset is to remove the header row from the copy
curSheet.AutoFilter.Range.Offset(1).Copy
curSheet.ShowAllData
Set targetBook = Application.Workbooks.Open "PathTo Total Hours"
Set targetSheet = targetBook.WorkSheet("DestinationSheet")
lastRow = Cells.Find(What:="*", After:=Range("A1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
targetSheet.Cells(lastRow + 1, 1).PasteSpecial
targetBook.Save
targetBook.Close
As you can see I put placeholders in for the specific setup of your workbook.
I know this is old, but for anyone else searching for how to do this, it can be done in a much more direct fashion:
Public Sub ExportRow()
Dim v
Const KEY = "Clarke, Matthew"
Const WS = "Sheet1"
Const OUTPUT = "c:\totalhours.xlsx"
Const OUTPUT_WS = "Sheet1"
v = ThisWorkbook.Sheets(WS).Evaluate("index(a:xfd,match(""" & KEY & """,a:a,),)")
With Workbooks.Open(OUTPUT).Sheets(OUTPUT_WS)
.[1:1].Offset(.[counta(a:a)]) = v
.Parent.Save: .Parent.Close
End With
End Sub