Can you write me an excel formula or VBA code that will do the following: In workbook…
- User
Can you write me an excel formula or VBA code that will do the following:
In workbook 'Service Providers Analysis' sheet 'TContractors' use the value in K2 to find the the matching sheet name in workbook 'Service Providers'. When the sheet name that corresponds to the value of K2 is found copy the value in D1 of the sheet found from workbook 'Service Providers' to A5 in sheet 'TContractors' in workbook 'Service Providers Analysis'
- Assistant
Here is the VBA code that accomplishes this task:
Sub CopyValueToSheet() Dim sourceWB As Workbook Dim destWB As Workbook Dim sourceSheetName As String Dim destSheet As Worksheet 'Set source workbook Set sourceWB = Workbooks("Service Providers Analysis.xlsx") 'Get value from cell K2 in TContractors sheet sourceSheetName = sourceWB.Sheets("TContractors").Range("K2").Value 'Check if the sheet exists in the source workbook If Not SheetExists(sourceSheetName, sourceWB) Then MsgBox "Sheet named '" & sourceSheetName & "' does not exist in the workbook 'Service Providers'." Exit Sub End If 'Set destination workbook Set destWB = Workbooks("Service Providers.xlsx") 'Copy the value from D1 in the source sheet to A5 in the destination sheet destWB.Sheets(sourceSheetName).Range("D1").Copy sourceWB.Sheets("TContractors").Range("A5").PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False End Sub Function SheetExists(sheetName As String, wb As Workbook) As Boolean Dim ws As Worksheet SheetExists = False For Each ws In wb.Worksheets If ws.Name = sheetName Then SheetExists = True Exit Function End If Next ws End Function