Create Hyperlink to sheet in cell VBA - vba

I have looked at many posts and cannot seem to get this right. I have a userform that take a codename and then creates a sheet with that name, then adds a link to the new sheet as the last cell in Column B on another sheet. I have used 3 different methods to insert the hyperlink, but all of them just return a blank cell, while if I change the value to any string, it works.
Dim sh As Worksheet
Dim codename As String
Dim lastrow As Long
Dim cont As Worksheet
On Error Resume Next
Application.ScreenUpdating = False
codename = InputBox("What is the codename?")
Sheets("XXX").Visible = True
Sheets("XXX").Copy After:=Worksheets("YYY")
ActiveWindow.ActiveSheet.name = codename
Sheets("XXX").Visible = False
Worksheets(YYY).Activate
lastrow = Sheets("YYY).Range("B" & Rows.Count).End(xlUp).Row + 1
ActiveSheet.Range("B" & lastrow).End(xlUp).Offset(1).Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:=sh & "!A1", TextToDisplay:=codename
ActiveSheet.Range("B" & lastrow).End(xlUp).Offset(2).Activate
ActiveCell.Hyperlinks.Add Anchor:=ActiveCell, Address:="", SubAddress:=sh.name & "!A1", TextToDisplay:=codename
ActiveSheet.Range("B" & lastrow).End(xlUp).Offset(3) = codename
ActiveSheet.Range("B" & lastrow).End(xlUp).Offset(4).Hyperlinks.Add Anchor:=Sheets(codename).Cells(1, 1), _
Address:="", SubAddress:=sh, TextToDisplay:=codename
Application.ScreenUpdating = True
I know I have 4 iterations of essentially the same thing. The point is is that no matter if I use 1 of them, or all 4, I get 3 blank cells and (codename) as plaintext, showing that I am obviously missing something easy that I for the life of me cannot figure out. Thanks to all responses.

The reason the links aren't working might be because you use the worksheet object sh without declaring it, and specifically, without declaring it as the new sheet.
In my solution I've only tested it using the .Add method that I included out-commented.
Sub test()
Dim sh As Worksheet, nsh As Worksheet ' sh = YYY, nsh = codename
Dim nrng As Range
Dim codename As String
Dim lastrow As Long
Dim cont As Worksheet
codename = InputBox("What is the codename?")
Set sh = Sheets("YYY")
Sheets("XXX").Visible = True
Sheets("XXX").Copy After:=Worksheets("YYY")
ActiveWindow.ActiveSheet.Name = codename
Sheets("XXX").Visible = False
'Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = codename ' if needed
sh.Activate
lastrow = sh.Range("B" & Rows.Count).End(xlUp).Row + 1
sh.Hyperlinks.Add _
Anchor:=sh.Range("B" & lastrow), _
Address:="", _
SubAddress:="'" & codename & "'!A1", _
TextToDisplay:=codename
End Sub
Shamelessly stolen from myself.

Sub Tester()
DoHyperlink Sheets("Sheet1").Range("F10"), _
Sheets("Sheet 2").Range("E12"), _
"Click Me"
End Sub
'assumes rngFrom and rngTo are in the same workbook...
Sub DoHyperlink(rngFrom As Range, rngTo As Range, LinkText As String)
rngFrom.Parent.Hyperlinks.Add Anchor:=rngFrom, Address:="", _
SubAddress:="'" & rngTo.Parent.Name & "'!" & rngTo.Address(), _
TextToDisplay:=LinkText
End Sub

If I get you right, you are trying to do this... But don't understand why it's "YYY" (not dynamic).
Option Explicit
Sub AddSheetAndLinkIt()
Dim codename As String
Dim oWS As Worksheet, oRng As Range
codename = InputBox("What is the codename?")
' Check if codename already exists
On Error Resume Next
Set oWS = ThisWorkbook.Worksheets(codename)
If Not oWS Is Nothing Then
MsgBox "The worksheet for """ & codename & """ already exists! You cannot create it again.", vbExclamation + vbOKOnly
Exit Sub
End If
' Copy worksheet "XXX" and add hyperlink to "YYY"
Set oWS = ThisWorkbook.Worksheets("YYY")
Set oRng = oWS.Range("B" & Rows.Count).End(xlUp)
ThisWorkbook.Worksheets("XXX").Copy After:=oWS
With ThisWorkbook.Worksheets("XXX (2)")
.Name = codename
.Visible = True
.Activate
End With
oWS.Hyperlinks.Add oRng, "", "'" & codename & "'!A1", "Go to " & codename, codename
Set oRng = Nothing
Set oWS = Nothing
End Sub

Related

VBA - Autofilter then copy the result into the new sheet

I am trying to do the macro which can do autofilter and copy the visible row , then paste them into the new sheet by using VBA. my code as below:
Option Explicit
Sub lab()
Dim ws As Worksheet
Dim sh1 As Worksheet
Dim mycoll As Collection
Set mycoll = New Collection
Set sh1 = ThisWorkbook.Sheets(1)
Dim rng As Range
Dim c As Range
Dim lastrow As Long
lastrow = Range("C" & Rows.Count).End(xlUp).Row
On Error Resume Next
Set rng = sh1.Range("B4:F" & lastrow)
With rng
.AutoFilter field:=2, Criteria1:=sh1.Range("I1"), Criteria2:=sh1.Range("I2"), Operator:=xlOr
.AutoFilter field:=3, Criteria1:=sh1.Range("K1"), Criteria2:=sh1.Range("K2"), Operator:=xlOr
.AutoFilter field:=4, Criteria1:=sh1.Range("M1"), Criteria2:=sh1.Range("M2"), Operator:=xlOr
End With
Set ws = Worksheets.Add
ws.Name = sh1.Range("I1").Value & "-" & sh1.Range("I2").Value
rng.SpecialCells(xlCellTypeVisible).Copy ws.Range("A1")
rng.AutoFilter
sh1.Activate
End Sub
my problem is the code only work correctly for the first new sheet. then it always create the sheet with the same content. I tried to find the root issue , could you please help assist on this ?
When there is a problem with your code, you never use On Error Resume Next! It only does not let VBA 'telling' you what problem the code has...
If your code names the newly created sheet using:
ws.Name = sh1.Range("I1").Value & "-" & sh1.Range("I2").Value
second time, if the concatenation of the two cells value is the same, VBA cannot name a sheet with the same name like an existing one. The raised error should have a clear description but your code jumps over it, because of On error Resume Next.
If you really need/want to use a similar sheet name, try placing a sufix. For doing that, you can use the next function:
Function shName(strName As String) As String
Dim ws As Worksheet, arrSh, arrN, maxN As Long, k As Long, El
ReDim arrSh(ActiveWorkbook.Sheets.count - 1)
For Each ws In ActiveWorkbook.Sheets
If ws.Name = strName Then
shName = strName & "_" & 1
Exit Function
End If
If InStr(ws.Name, strName & "_") > 0 Then arrSh(k) = ws.Name: k = k + 1
Next
If k = 0 Then shName = strName: Exit Function 'if no such a name exists
ReDim Preserve arrSh(k - 1)
'determine the bigger suffix:
For Each El In arrSh
arrN = Split(El, "_")
If CLng(arrN(UBound(arrN))) > maxN Then maxN = CLng(arrN(UBound(arrN)))
Next
shName = strName & "_" & maxN + 1
End Function
It should be called from your existing code replacing the line
ws.Name = sh1.Range("I1").Value & "-" & sh1.Range("I2").Value
with
ws.Name = shName(sh1.Range("I1").Value & "-" & sh1.Range("I2").Value)

Create a hyperlink list of sheets in excel

I know how to populate a sheet with specific hyperlinks to all the sheets in a given workbook, but how do I exclude certain sheets from being listed?
I have listed the VB below for what I was using. I would like to exclude certain sheets like "Test Results" etc.
Sub GetHyperlinks()
Dim ws As Worksheet
Dim i As Integer
i = 9
For Each ws In ThisWorkbook.Worksheets
ActiveWorkbook.Sheets("overview").Hyperlinks.Add _
Anchor:=ActiveWorkbook.Sheets("overview").Cells(i, 1), _
Address:="", _
SubAddress:="'" & ws.NAme & "'!A1", _
TextToDisplay:=ws.NAme
i = i + 1
Next ws
End Sub
Sub GetHyperlinks()
Dim arrExclude
Dim ws As Worksheet
Dim i As Integer
'Sheets to be excluded from linking
arrExclude = Array("Test Results", "some other sheet", "overview")
i = 9
For Each ws In ThisWorkbook.Worksheets
'test to see if not excluded
If IsError(Application.Match(ws.Name, arrExclude, 0)) Then
ActiveWorkbook.Sheets("overview").Hyperlinks.Add _
Anchor:=ActiveWorkbook.Sheets("overview").Cells(i, 1), _
Address:="", _
SubAddress:="'" & ws.Name & "'!A1", _
TextToDisplay:=ws.Name
i = i + 1
End If 'include this sheet
Next ws
End Sub

excel copy all from workbook 2, paste in workbook [duplicate]

This question already has answers here:
Copy from one workbook and paste into another
(2 answers)
Closed 5 years ago.
I am trying to copy all data from a workbook on my server and paste the values to B2 in another workbook.
This is what I have so far. It brings me to the workbook 2, but I have to manually select all and copy then paste in workbook 1.
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim LastRow As Long
Dim StartCell As Range
Set sht = Sheet5
Set reportsheet = Sheet5
Set StartCell = Range("B2")
'Refresh UsedRange
Worksheets("TSOM").UsedRange
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Select Range
sht.Range("B2:B" & LastRow).Select
With Range("B2:B" & LastRow)
If MsgBox("Clear all Transmission Stock data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N2000").ClearContents
MsgBox ("Notes:" & vbNewLine & vbNewLine & _ 'This is not needed if I can automate the copy and paste.
"Copy ALL" & vbNewLine & _
"Paste as Values")
End If
End With
Workbooks.Open "P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx"
ThisWorkbook.Activate
reportsheet.Select
Range("B2").Select
whoa: 'If filename changes then open folder
Call Shell("explorer.exe" & " " & "P:\ESO\1790-ORL\OUC\_Materials\Stock Status", vbNormalFocus)
Range("B2").Select
Application.ScreenUpdating = True
End Sub
Thanks
A few guesses as you haven't provided all the details
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim LastRow As Long
Dim StartCell As Range
Dim sht As Worksheet
Dim wb As Workbook
Set sht = Sheet5
Set StartCell = sht.Range("B2")
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If MsgBox("Clear all Transmission Stock data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N2000").ClearContents
End If
Set wb = Workbooks.Open("P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx")
wb.Sheets(1).UsedRange.Copy
StartCell.PasteSpecial xlValues
Application.ScreenUpdating = True
End Sub
Avoid SendKeys, and since you are pasting values only, you don't need to use either Copy or Paste/PasteSpecial.
With wsCopyFrom.Range("A1:N3000")
wsCopyTo.Range("B2").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
Here are several other ways to copy values from one file to another:
Copy from one workbook and paste into another
This is what I got to work. It brings up a select file folder and copies all the data from it into my current workbook. It then names B1 (my header) with the filename without the extension.
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Dim s As String
Set mycell = Worksheets("TSOM").Range("B1")
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
If MsgBox("Update transmission Stock Status data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N3000").ClearContents
Else: Exit Sub
End If
'Locate file to copy data from
vFile = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
'Assign filename to Header
s = Mid(vFile, InStrRev(vFile, "\") + 1)
s = Left$(s, InStrRev(s, ".") - 1)
mycell.Value = s
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
'Copy Range
wsCopyFrom.Range("A1:N3000").Copy
wsCopyTo.Range("B2").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
SendKeys "Y"
SendKeys ("{ESC}")
'Close file that was opened
wbCopyFrom.Close SaveChanges:=False
Application.Wait (Now + 0.000005)
Call NoSelect
Exit Sub
End Sub

Need a VBA code to select sheets matching names in list then save to a new workbook

I have a little tricky VBA I'm trying to create. What I currently have is two other macros which search two sheets for vendor names and creates new sheets with their specific information. This leaves me with approx 40 sheets, now what I'm trying to do is write a macro that will search for the vendor name in the sheet title and save all the sheets associated with that vendor to a new workbook (if a file exists update the current sheets in that workbook). I will have a list of vendors in one sheet that I would like to use as the search criteria. Here is an example of the first macro I run
Sub ERP_POS()
Dim ws1 As Worksheet Dim wsNew As Worksheet
Dim rng As Range
Dim r As Integer
Dim c As Range
Dim bAF As Boolean
Set ws1 = Sheets("ERP_POS")
Set rng = Range("Database") bAF = ws1.AutoFilterMode
'extract a list of Sales Reps With ws1
.Columns("P:P").Copy _
Destination:=.Range("X1")
.Columns("X:X").AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=.Range("Y1"), Unique:=True
r = .Cells(Rows.Count, "Y").End(xlUp).Row
.Columns("X:X").ClearContents
'set up Criteria Area
.Range("X1").Value = .Range("P1").Value
For Each c In .Range("Y2:Y" & r)
'add the rep name to the criteria area
.Range("X2").Value = _
"=""="" & " & Chr(34) & c.Value & Chr(34)
'add new sheet (if required)
'and run advanced filter
If WksExists("ERP_POS" & " " & c.Value) Then
Sheets("ERP_POS" & " " & c.Value).Cells.Clear
rng.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=.Range("X1:X2"), _
CopyToRange:=Sheets("ERP_POS" & " " & c.Value).Range("A1"), _
Unique:=False
Else
Set wsNew = Sheets.Add
wsNew.Move After:=Worksheets(Worksheets.Count)
wsNew.Name = "ERP_POS" & " " & c.Value
rng.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=.Range("X1:X2"), _
CopyToRange:=wsNew.Range("A1"), _
Unique:=False
End If
Next
.Select
.Columns("Y:X").EntireColumn.Delete
If bAF = True Then
.Range("A1").AutoFilter
End If
End With
End Sub
Function WksExists(wksName As String) As Boolean
On Error Resume Next
WksExists = CBool(Len(Worksheets(wksName).Name) > 0)
End Function
And here is where I have gotten using that and recoring my own macro but haven't figured out how to create the array function with variables derived from the search, or to get the search to work at creating the c.value.
Sub Test1234() ' ' Test1234 Macro ' Dim ws As Worksheet Dim ws2 As
Worksheet ws = Worksheet.Name
For Each ws In ActiveWorkbook.Worksheets
If ws.Name Like "*CompanyA*" Then
Set ws2 = Worksheet.Name
Sheets(ws2).Select
Sheets(ws2).Copy
ActiveWorkbook.SaveAs filename:="C:\Users\xxxxx\Desktop\Lovley.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If
Next ws
End Sub
Try this code:
Option Explicit
Option Base 1 'Ensure to have this command at the top of the module
Sub Lst_Vendors_Wbk_Set()
Const kPath As String = "D:\StackOverFlow\Answers\" 'Change as required
Dim rTrg As Range, rCll As Range, sVendor As String
'Assuming list of vendors is located at Wsh [Vendors] Column [A] - change as required
With ThisWorkbook.Sheets("Vendors")
Rem Set Target Range
Set rTrg = .Range("A2:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
Rem Work List of Vendors
For Each rCll In rTrg.Cells
sVendor = rCll.Value2
If Not sVendor = Empty Then
If Not (Wsh_Find_And_Copy_To_New_Wbk(sVendor, kPath)) Then
MsgBox "No sheet found for vendor: [" & sVendor & "]"
End If: End If: Next: End With
End Sub
Function Wsh_Find_And_Copy_To_New_Wbk(sKey As String, sPathFilename As String) As Boolean
Dim Wsh As Worksheet, aWsh() As String
Rem Validate Key
If sKey = Empty Then GoTo ExitTkn
Rem Get Worksheet Array To Be Copied Into A New Wbk
If IsEmpty(aWsh) Then Stop
For Each Wsh In ThisWorkbook.Worksheets
If Wsh.Name Like "*" & sKey & "*" Then
On Error Resume Next
ReDim Preserve aWsh(1 + UBound(aWsh))
If err.Number <> 0 Then ReDim Preserve aWsh(1)
On Error GoTo 0
aWsh(UBound(aWsh)) = Wsh.Name
End If: Next
Rem Copy Worksheet Array Into A New Wbk
On Error GoTo ExitTkn
ThisWorkbook.Sheets(aWsh).Copy
ActiveWorkbook.SaveAs Filename:=sPathFilename & sKey, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Rem Set Results
Wsh_Find_And_Copy_To_New_Wbk = True
ExitTkn:
End Function
Suggest to visit the following pages:
Excel Objects, For Each...Next Statement, On Error Statement
Range Object (Excel), Variables & Constants, Workbook Object (Excel)
Worksheet Object (Excel), With Statement

Copy data from one workbook to new workbook in excel VB

I want to copy selected columns of a file from a worksheet to a new workbook using VBS in Excel. The following code gives the empty columns in new file.
Option Explicit
'Function to check if worksheets entered in input boxes exist
Public Function wsExists(ByVal WorksheetName As String) As Boolean
On Error Resume Next
wsExists = (Sheets(WorksheetName).Name <> "")
On Error GoTo 0 ' now it will error on further errors
End Function
Sub createEndUserWB()
Dim i As Integer
Dim colFound As String
Dim b(1 To 1) As Integer
Dim Sheet_Copy_From As String
Dim newSheet As String
Dim colVal As Variant 'sheet name from array to test
Dim colNames As Variant 'Array
Dim col As Variant
Dim colN As Integer
Dim lkr As Range
Dim destWS As Worksheet
Dim endUserWB As Workbook
Dim lastRow As Integer
'Application.ScreenUpdating = False 'Speeds up the routine by not updating the screen.
'IMPORTANT, remember to turn screen updating back on before the routine ends
'***** ENTERING WORKSHEET NAMES *****
'Get the name of the worksheet to be copied from
Sheet_Copy_From = Application.InputBox(Prompt:= _
"Please enter the sheet name you which to copy from", _
Title:="Sheet_Copy_From", Type:=2) 'Type:=2 = text
If Sheet_Copy_From = "False" Then 'If Cancel is clicked on Input Box exit sub
Exit Sub
End If
'*****CHECK TO SEE IF WORKSHEETS EXIST (USES FUNCTION AT VERY TOP)*****
Select Case wsExists(Sheet_Copy_From) 'calling function at very top
Case False
MsgBox "The worksheet named """ & Sheet_Copy_From & """ is either missing" & vbNewLine & _
"or spelt incorrectly" & vbNewLine & vbNewLine & _
"Please rectify and then run this procedure again" & vbNewLine & vbNewLine & _
"Select OK to exit", _
vbInformation, ""
Exit Sub
End Select
Set destWS = ActiveWorkbook.Sheets(Sheet_Copy_From)
'array of sheet names to test for
colNames = Array("SID", "First Name", "Last Name", "xyz", "Telephone Number", "Department")
'Get the name of the worksheet to pasted into
newSheet = Application.InputBox(Prompt:= _
"Please enter the sheet name you which to paste in", _
Title:="New File", Type:=2) 'Type:=2 = text
If newSheet = "False" Then 'If Cancel is clicked on Input Box exit sub
Exit Sub
End If
Set endUserWB = Workbooks.Add
endUserWB.SaveAs Filename:=newSheet
endUserWB.Sheets(1).Name = "Sheet1"
'endUserWS.Name = "End User"
'Copy Columns 1 by 1
i = 1
For Each col In colNames
On Error GoTo colNotFound
colN = destWS.Rows(1).Find(col, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False).Column
lastRow = destWS.Cells(Rows.Count, colN).End(xlUp).Row
'MsgBox "Column for " & colN & " is " & lastRow, vbInformation, ""
'Copy paste Part begins here
If colN <> -1 Then
'destWS.Select
'colVal = destWS.Columns(colN).Select
'Selection.Copy
'endUserWB.ActiveSheet.Columns(i).Select
'endUserWB.ActiveSheet.PasteSpecial Paste:=xlPasteValues
'endUserWB.Sheets(1).Range(Cells(2, i), Cells(lastRow, i)).Value = destWS.Range(Cells(2, colN), Cells(lastRow, colN))
destWS.Range(2, lastRow).Copy
endUserWB.Worksheets("Sheet1").Range(2).PasteSpecial (xlPasteValues)
End If
i = i + 1
Next col
Application.CutCopyMode = False 'Clears the clipboard
'MsgBox "Column """ & colN & """ is Found",vbInformation , ""
colNotFound:
colN = -1
Resume Next
End Sub
What is wrong with code? Any other method to copy? I followed the answer at Copy from one workbook and paste into another as well. But it also gives blank sheet.
If I understood it right try changing this part of your code:
destWS.Range(2, lastRow).Copy
endUserWB.Worksheets("Sheet1").Range(2).PasteSpecial (xlPasteValues)
by:
destWS.Activate
destWS.Range(Cells(2, colN), Cells(lastRow, colN)).Copy
endUserWB.Activate
endUserWB.Worksheets("Sheet1").Cells(2, colN).PasteSpecial (xlPasteValues)