VBA send cells value to another sheets next empty cell - excel

I am trying to send a ticker from one workbook to another when ever it is one I would like to track. When I send it to the other workbook I want to paste the ticker in the next open cell in column JW.
So far my code is as follows:
Sub S2WL()
Dim lst As Long
Dim myVar As String
myVar = ActiveWorkbook.Activesheet.Range(“C2”).Value
With Workbooks("Dash").Sheet("DASH")
lst = .Range("JW" & Rows.Count).End(xlUp).Row + 1
.Range("JW" & lst).PasteSpecial xlPasteValues
End With
End Sub
I'm still very new to VBA and it fails when attempting to pull from my active sheet in workbook Fundamentals. I have multiple sheets that are basically copies in fundamentals. I want a general macro to send C2's value for whatever sheet I am on in Fundamentals to my watchlist in the Workbook Dash column JW. And each time to the next open cell in that column.
Thank you for any and all help!

Copy Value From the Active Sheet
A Qick Fix
Sub S2WLFixed()
Dim MyValue As Variant: MyValue = ThisWorkbook.ActiveSheet.Range("C2").Value
With Workbooks("Dash.xlsx").Worksheets("Dash")
Dim lst As Long: lst = .Cells(.Rows.Count, "JW").End(xlUp).Row + 1
.Cells(lst, "JW").Value = MyValue
End With
End Sub
An Improvement
The following covers most of the issues you may encounter when using the previous code.
Sub S2WL()
' 1. Define constants.
Const ProcName As String = "S2WL" ' for the message boxes
' s - Source (read from)
Const sCellAddress As String = "C2"
' d - Destination (write to)
Const dwbName As String = "Dash.xlsx" ' check if file extension is correct!
Const dwsName As String = "Dash"
Const dColumn As String = "JW"
' 2. Reference the source...
' Reference the workbook containing this code ('swb').
Dim swb As Workbook: Set swb = ThisWorkbook
' Reference the active sheet ('ash').
Dim ash As Object: Set ash = ActiveSheet
' Validate that the active sheet is in the source workbook.
If Not ash.Parent Is swb Then
MsgBox "The active sheet '" & ash.Name & "' is not located in the '" _
& swb.Name & "' workbook.", vbCritical, ProcName
Exit Sub
End If
' Validate that the active sheet is a worksheet.
If ash.Type <> xlWorksheet Then
MsgBox "The active sheet '" & ash.Name & "' is not a worksheet.", _
vbCritical, ProcName
Exit Sub
End If
' Reference the source cell ('sCell').
Dim sCell As Range: Set sCell = ash.Range(sCellAddress)
' 3. Reference the destination...
' Validate the destination workbook ('dwb').
Dim dwb As Workbook
On Error Resume Next
Set dwb = Workbooks(dwbName)
On Error GoTo 0
If dwb Is Nothing Then
MsgBox "The destination workbook '" & dwbName & "' is not open.", _
vbCritical, ProcName
Exit Sub
End If
' Validate the destination worksheet ('dws').
Dim dws As Worksheet
On Error Resume Next
Set dws = dwb.Worksheets(dwsName)
On Error GoTo 0
If dws Is Nothing Then
MsgBox "The destination worksheet '" & dwsName _
& "' does not exist in the '" & dwbName & "' workbook.", _
vbCritical, ProcName
Exit Sub
End If
' Reference the destination cell ('dCell').
Dim dCell As Range
Set dCell = dws.Cells(dws.Rows.Count, dColumn).End(xlUp).Offset(1)
' 4. Copy.
' Write the value from the source cell to the destination cell.
dCell.Value = sCell.Value
' Save the destination workbook (decide on your own).
'dwb.Save
' 5. Inform.
MsgBox "Value copied.", vbInformation
End Sub

Related

Filtering data and copying it to a new sheet

I have a survey with health data from patients. I have a sheet with all the data named "data",
This is how the data sheet looks like, each column being some category from the patient (there are more rows):
I am creating a macro where the user has to select a Health Authority from a drop-down box, and that will create a new sheet named as the health authority selected. The button assigned to the macro is on another sheet called "user".
This is my code so far:
EDIT: I added sub demo () to try and paste it but it did not work. It says variable not defined in the part " With Sheets(sName)"
Option Explicit
Sub createsheet2()
Dim sName As String, ws As Worksheet
sName = Sheets("user").Range("M42").Value
' check if already exists
On Error Resume Next
Set ws = Sheets(sName)
On Error GoTo 0
If ws Is Nothing Then
' ok add
Set ws = Sheets.Add(after:=Sheets(Sheets.Count))
ws.Name = sName
MsgBox "Sheet created : " & ws.Name, vbInformation
Else
' exists
MsgBox "Sheet '" & sName & "' already exists", vbCritical, "Error"
End If
End Sub
Sub demo()
Const COL_HA = 6 ' F
Dim id As Long, rng As Range
id = 20 ' get from user dropdown
With Sheets("user")
.AutoFilterMode = False
.UsedRange.AutoFilter field:=COL_HA, Criteria1:=id
Set rng = .UsedRange.SpecialCells(xlVisible)
End With
' new sheet
'here is the problem
With Sheets(sName)
rng.Copy .Range("A1")
.Range("A1").Activate
End With
End Sub
I need to write the code that inserts in the new sheet only the data of the patients of the chosen Health Authority. Each Health Authority corresponds to a number
"sha" column is the health authority that the user previously selected.
Does anyone know how to insert the data I need to this new created sheet?
I think that I need to filter the data first and then paste it inside the sheet. I am very new at VBA and I'm lost.
Replace your code with this
Option Explicit
Sub createsheet()
Const COL_HA = 6 ' F on data sheet is Health Auth
Dim sName As String, sId As String
Dim wsNew As Worksheet, wsUser As Worksheet
Dim wsIndex As Worksheet, wsData As Worksheet
Dim rngName As Range, rngCopy As Range
With ThisWorkbook
Set wsUser = .Sheets("user")
Set wsData = .Sheets("data")
Set wsIndex = .Sheets("index")
End With
' find row in index table for name from drop down
sName = Left(wsUser.Range("M42").Value, 30)
Set rngName = wsIndex.Range("L5:L32").Find(sName)
If rngName Is Nothing Then
MsgBox "Could not find " & sName & " on index sheet", vbCritical
Else
sId = rngName.Offset(, -1) ' column to left
End If
' create sheet but check if already exists
On Error Resume Next
Set wsNew = Sheets(sName)
On Error GoTo 0
If wsNew Is Nothing Then
' ok add
Set wsNew = Sheets.Add(after:=Sheets(Sheets.Count))
wsNew.Name = sName
MsgBox "Sheet created : " & wsNew.Name, vbInformation
Else
' exists
MsgBox "Sheet '" & sName & "' already exists", vbCritical, "Error"
Exit Sub
End If
' filter sheet and copy data
Dim lastrow As Long, rngData As Range
With wsData
lastrow = .Cells(.Rows.Count, COL_HA).End(xlUp).Row
Set rngData = .Range("A10:Z" & lastrow)
.AutoFilterMode = False
rngData.AutoFilter Field:=COL_HA, Criteria1:=sId
Set rngCopy = rngData.SpecialCells(xlVisible)
.AutoFilterMode = False
End With
' new sheet
With wsNew
rngCopy.Copy .Range("A1")
.Range("A1").Activate
End With
MsgBox "Data for " & sId & " " & sName _
& " copied to wsNew.name", vbInformation
End Sub

Copy entire row from one workbook to another

I need a macro that can copy the entire row from the workbook I am in based on the cell I have selected. I can do this already, using the following:
ActiveCell.EntireRow.Select
Selection.Copy
But then, I need it to paste that (formatting and all) into the first empty row (based on column B) of a workbook that is closed. R:\dasboards\wo.xlsm
Backup Entire Row to a Closed Workbook
Adjust the values in the constants section.
Option Explicit
Sub BackupEntireRow()
Const dFilePath As String = "R:\DashBoards\wo.xlsm"
Const dwsName As String = "Sheet1"
Const dlrCol As String = "B"
Dim IsSuccess As Boolean
If TypeName(Selection) <> "Range" Then
MsgBox "No cells selected.", vbCritical
Exit Sub
End If
Dim dwbName As String: dwbName = Dir(dFilePath)
If Len(dwbName) = 0 Then
MsgBox "Could not find the destination file" _
& vbLf & "'" & dFilePath & "'", vbCritical
Exit Sub
End If
Dim srrg As Range: Set srrg = ActiveCell.EntireRow
Dim dwb As Workbook
Dim dDoCloseWorkbook As Boolean
On Error Resume Next
Set dwb = Workbooks(dwbName)
On Error GoTo 0
If dwb Is Nothing Then
Set dwb = Workbooks.Open(dFilePath)
dDoCloseWorkbook = True
End If
Dim dws As Worksheet
On Error Resume Next
Set dws = dwb.Worksheets(dwsName)
On Error GoTo 0
If dws Is Nothing Then
If dDoCloseWorkbook Then
dwb.Close SaveChanges:=False
End If
MsgBox "The destination worksheet '" & dwsName & "' doesn't exist.", _
vbCritical
Exit Sub
End If
Dim dCell As Range
Set dCell = dws.Cells(dws.Rows.Count, dlrCol).End(xlUp).Offset(1)
Dim drrg As Range: Set drrg = dCell.EntireRow
srrg.Copy drrg
If dDoCloseWorkbook Then
dwb.Close SaveChanges:=True
Else
dwb.Save
End If
IsSuccess = True
If IsSuccess Then
MsgBox "Row backed up.", vbInformation
End If
End Sub

Object Doesn't Support this Property or Method When copying from another workbook

I'm trying to write a small code in Excel that lets me open in the background another workbook, copy a range of data in there, and then pasty it in the active workboo. Should be pretty straight forward but for some reason I'm getting this error. So far what I've got is this, and I know the error comes from this line "cpyLastRow = ImportBook.cpySheet.Cells(3, 1).End(xlDown).Row", Ive got some variables commented to make it a little bit mor dyanimc in the future. Any ideas?
Private Sub CommandButton2_Click()
Dim OpenFile As Variant
Dim ImportBook As Workbook
Dim cpySheet As Worksheet
Dim cpyLastRow As Long
Dim cpyLastColumn As Long
'Dim cpyStartCell As Range
Set cpySheet = Sheets("DAO")
'Set cpyStartCell = Range("C3")
Application.ScreenUpdating = False
OpenFile = Application.GetOpenFilename(Title:="Select a file to import data", filefilter:="Excel Files (*.xls*),*xls*")
If OpenFile <> False Then
Set ImportBook = Application.Workbooks.Open(OpenFile)
cpyLastRow = ImportBook.cpySheet.Cells(3, 1).End(xlDown).Row
'cpyLastColumn = cpyStartCell.Column
ImportBook.cpySheet.Range("C3", cpySheet.Cells(cpyLastRow, 3)).Copy
ThisWorkbook.ActiveSheet.Range("C3").PasteSpecial xlPasteValues
ImportBook.Close False
End If
Application.ScreenUpdating = True
End Sub
You get an error due to mixing import workbook property and active worbook sheet reference. Try to use method 1 or method 2. Be sure to specify actual sheet name in the import workbook.
'get reference to sheet "ABF - DAO" in active workbook
Set cpySheet = Sheets("ABF - DAO")
...
'error: mix workbook property and sheet reference
cpyLastRow = ImportBook.cpySheet.Cells(3, 1).End(xlDown).Row
'method 1: get reference to sheet in import workbook
Set cpySheet = ImportBook.Sheets("ABF - DAO")
cpyLastRow = cpySheet.Cells(3, 1).End(xlDown).Row
'method 2: get last row without sheet reference
cpyLastRow = ImportBook.Sheets("ABF - DAO")
Copy Column Range From Closed Workbook
Option Explicit
Private Sub CommandButton2_Click()
Const ProcName As String = "CommandButton2_Click"
On Error GoTo clearError
Const sTitle As String = "Select a file to import data"
Const sFilter As String = "Excel Files (*.xls*),*xls*"
Const sName As String = "DAO"
Const sFirst As String = "C3"
Const dFirst As String = "C3"
Dim dSuccess As Boolean
' Source
' Path
Dim sPath As Variant
sPath = Application.GetOpenFilename(Title:=sTitle, FileFilter:=sFilter)
If sPath = False Then
MsgBox "You canceled.", vbExclamation, "Canceled"
GoTo ProcExit
End With
Application.ScreenUpdating = False
' Worksheet
Dim swb As Workbook: Set swb = Workbooks.Open(sPath)
On Error Resume Next
Dim sws As Worksheet: Set sws = swb.Worksheets(sName)
On Error GoTo 0
If sws Is Nothing Then
CloseWithoutSaving swb
MsgBox "The worksheet '" & sName & "' does not exist.", _
vbCritical, "No Worksheet"
GoTo ProcExit
End If
' Range
Dim fCell As Range: Set fCell = sws.Range(sFirst)
With fCell
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then
CloseWithoutSaving swb
MsgBox "No data.", vbCritical, "No Data"
GoTo ProcExit
End If
Dim srg As Range: Set srg = .Resize(lCell.Row - .Row + 1)
End With
' Destination
' Assuming that the button is on the Destination Worksheet.
Dim dCell As Range: Set dCell = Range(dFirst)
' Otherwise, you should do something like this:
'Set dCell = ThisWorkbook.Worksheets("DAO").Range(dFirst)
' Copy (by Assignment)
dCell.Resize(srg.Rows.Count).Value = srg.Value
CloseWithoutSaving swb
dSuccess = True
ProcExit:
If Not Application.ScreenUpdating Then
Application.ScreenUpdating = True
End If
If dSuccess Then
MsgBox "Data transferred.", vbInformation, "Success"
End If
Exit Sub
clearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Sub
Sub CloseWithoutSaving( _
ByVal wb As Workbook)
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End Sub

Selecting a sheet with a dynamic name which contains a date

I have been trying to select one of the sheets called "SYS 6.10.2020". However, this sheet changes its date every week. Is there a VBA code that code could select the sheet based on today's date?
Worksheet Name
The Code
Option Explicit
' If it is the only worksheet that starts with "SYS ", "sys "...
Sub PartialMatch()
Const wsName As String = "SYS "
Dim wb As Workbook
Set wb = ThisWorkbook
Dim ws As Worksheet
For Each ws In wb.Worksheets
If StrComp(Left(ws.Name, Len(wsName)), wsName, vbTextCompare) = 0 Then
Exit For
End If
Next
If ws Is Nothing Then
'MsgBox "Worksheet starting with '" & wsName _
& "' not found.", vbCritical, "Fail"
Debug.Print "Worksheet starting with '" & wsName & "' not found."
Exit Sub
End If
' Continue with code...
Debug.Print ws.Name
End Sub
Sub ExactMatch()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim wsName As String
wsName = "SYS " & Replace(Format(Date, "d/m/yyyy"), "/", ".")
On Error Resume Next
Dim ws As Worksheet
Set ws = wb.Worksheets(wsName)
On Error GoTo 0
If ws Is Nothing Then
'MsgBox "Worksheet '" & wsName & "' not found.", vbCritical, "Fail"
Debug.Print "Worksheet '" & wsName & "' not found."
Exit Sub
End If
' Continue with code...
Debug.Print ws.Name
End Sub
Static String
You can do it by supplying the date (formatted in the appropriate format) to the Sheets function.
Quick Sample:
Sheets("SYS 6.10.2020").Select
Dynamic String
Sub Task1()
Dim myDate
myDate = Date
MsgBox myDate
Dim LValue As String
LValue = "SYS " & Format(myDate, "dd.mm.yyyy")
MsgBox LValue
Sheets(LValue).Activate
End Sub
If there is only one sheet added per week, you could use the calendar within vba to find the last date (e.g. last monday) and generate the name from that.

Copy workbook and to paste below another workbook MS Excel

First I open a SubWorkbook than copy data from worksheet to update MainWorkbook (paste below):
The problem occur when I try to set variable for worksheet from the workbook I just open. It said: "Subscript out of Range".
What happen to it and how I can fix it, or is it wrong direction that I have to go from another way.
Sub Data_Inbound()
Dim mywb As Workbook
Dim FName As String
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long
Set mywb = ActiveWorkbook
On Error GoTo errHandler:
FName = Application.GetOpenFilename(filefilter:="Excel Files,*.xlsx*", Title:="Please select an Excel file")
Workbooks.Open FileName:=FName
Set wsCopy = Workbooks(FName).Worksheets(Sheet1)
Set wsDest = Workbooks(mywb).Worksheets(Sheet1)
lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row
wsCopy.Range("A2" & lCopyLastRow).Copy _
wsDest.Range("A" & lDestLastRow)
wsDest.Activate
errHandler:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Data_Inbound"
Exit Sub
End Sub
I see other guy they have the same question, but they use worksheet name, for me I use a variant variable, but it lead to error:
Other guy:
Set wsCopy = Workbooks("Warranty Template.xlsm").Worksheets("PivotTable")
Copy/Paste From Closed Workbook
The code has run successfully if you see the message. If not, something went wrong, and there is a message in the Immediate window CTRL+G.
The Code
Option Explicit
Sub Data_Inbound()
' Initialize error handling.
Const ProcName As String = "Data_Inbound"
' Do not use error handling while developing the code.
On Error GoTo clearError ' Turn on error trapping.
' Define Destination Workbook.
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Define Source Workbook Name.
Dim srcName As String
srcName = Application.GetOpenFilename(filefilter:="Excel Files,*.xlsx*", _
Title:="Please select an Excel file")
' Open Source Workbook (No variable, but it is the active one).
Workbooks.Open Filename:=srcName
' Define Source Worksheet ('wsSource').
Dim wsSource As Worksheet
Set wsSource = ActiveWorkbook.Worksheets("Sheet1") ' Note the double quotes.
' Define Destination Worksheet ('wsDest')
Dim wsDest As Worksheet
Set wsDest = wb.Worksheets("Sheet1") ' Note the double quotes...
' ... and not: Set wsDest = Workbooks(wb).Worksheets("Sheet1") - wrong!
' Define Source Last (Non-Empty) Row ('srcLastRow').
Dim srcLastRow As Long
srcLastRow = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row
' Define Destination First (Empty (available)) Row ('destFirstRow').
Dim destFirstRow As Long
destFirstRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row
' Copy from Source to Destination.
wsSource.Range("A2:A" & srcLastRow).Copy wsDest.Range("A" & destFirstRow)
' Note "A2:A" and not: "A2" - wrong!
' Now you wanna close the Source Workbook, but how?
' You can use the 'Parent' property:
wsSource.Parent.Close False ' False means not to save changes.
' If you closed, wsDest is active again so you don't need:
'wsDest.Activate
' Inform user, so you know the code has finished.
MsgBox "Copied data.", vbInformation, "Success"
ProcExit:
Exit Sub
clearError:
Debug.Print "'" & ProcName & "': " & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
On Error GoTo 0 ' Turn off error trapping.
GoTo ProcExit
End Sub

Resources