I am creating a vba For loop to cycle through cells in a range and creating a hyperlink to file folders based on the text within the cell. See below:
Set rng = Worksheets("Sheet1").Range("A1:A100")
For Each cell In rng
address1 = "C:\Users\Desktop\Tests\Comm Review\Item #" &
cell.Text
If Not IsEmpty(cell) Then
Worksheets("Sheet1").Hyperlinks.Add Anchor:=cell, Address:=address1, TextToDisplay:=cell.Text
End If
Next cell
The cell value will be something like 1001.T0502 and the actual folder name that I am linking to will be Item #1001.T0502. So in my address1 variable i create the path to the folder.
However, when I do this it creates the path with everything but #1001.T0502 and ends up stopping at "\Item". If I were to drop the number sign(#) though it includes the number and ends up being Item 1001.T0502. For some reason the number sign stops it from making the correct path. What am I missing here? There are already 200 folders with the number sign in the folder name so going back now and taking it out would be too much work.
Any help would be appreciated. Thanks!
You cannot use a pound character in a file name for a hyperlink in an Office program. See official Microsoft documentation here:
https://support.microsoft.com/en-us/help/202261/you-cannot-use-a-pound-character-in-a-file-name-for-a-hyperlink-in-an
Seems totally wacko if you ask me, but alas, I think you're trying to solve an unsolvable problem.
But, fear not, I did think of a potential work around. Instead of making the cells actual hyperlinks, you could just recolor the cell to blue with an underline and then use this little trick to capture when the cell is selected and open Windows Explorer to the corresponding file path.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Selection.Count = 1 Then
If Not Intersect(Target, Range("A1:A100")) Is Nothing Then
Shell "explorer ""C:\Users\Desktop\Tests\Comm Review\Item #" & Target.Value & """", vbNormalFocus
End If
End If
End Sub
The only downside I can see here is that selecting the cell with the arrow keys also opens the corresponding folder. There may be a work around to that, but I don't have time at the moment to research it.
I hope this helps!
Related
Could anyone from this group can offer some advice on the problem I'm trying to solve? I was attempting to open a PDF document to a specific page using the Excel Hyperlink function. I tried to solve this mystery but to no avail. Hope someone can provide me their thoughts and ideas.
I tried Google and Youtube but only few were related to my issue and the solution discussed was not working on my situation... or maybe i missed something. This will be a great help for me once the issue is solved. Thank you in advance.
Using a macro enabled workbook you can hi-jack the hyperlink open event but it isn't as dynamic as we would hope it to be. Unfortunately, we cannot cancel any followed hyperlink using Worksheet_FollowHyperlink so we need to find a way around following a direct hyperlink.
We can create a hyperlink which goes nowhere by referencing itself then set the text to display as "Follow Link". Because the cell reference is then in the hyperlink, we can use an offset from that to get the desired address and sub address from the column before it; which then allows us to open the PDF at the desired place.
Unfortunately, the hyperlink if copied down will still reference the original cell, so each link would need to be edited separately. To date I haven't found a way to use the HYPERLINK function successfully.
The hyperlink format in the cell to the left would need to be the full path appended with "#page=" and the relevant page; e.g. C:\links\blah.pdf#page=6
In the worksheet module
Const AcrobatReader = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
If Target.TextToDisplay = "Follow Link" Then
Dim Ref As String: Ref = Range(Target.SubAddress).Offset(0, -1).Text
Dim URL() As String: URL = Split(Ref, "#page=")
If UBound(URL) > 0 Then Call OpenPDFtoPage(URL(0), CLng(URL(1)))
End If
End Sub
Function OpenPDFtoPage(FilepathPDF As String, page As Long)
Dim Path As String: Path = AcrobatReader & " /A ""page=" & page & """ " & FilepathPDF
Shell Path, vbNormalFocus
End Function
The AcroRd32.exe path may need updating for specific installations
Maybe having just one "Follow Link" hyperlink where the URL in the cell next to it is more dynamic may allow this to be a bit more useable.
I'm trying to use the GoTo command in Excel to GoTo a variable cell value, but I'm struggle how to get the cell address into VBA, any thoughts?
Within my Excel document I have defined the name of a cell (i.e. created a range), lets call it "x" for ease, that contains the cell address, for example $B$3. However it's important to note the value within the range changes as I modify the document, it's not static.
I have tried
Application.GoTo Range("x")
and
Application.GoTo Range("x").value
but neither of these seem to work.
Can I achieve what I need to using GoTo or should I be using a different command entirely?
The context should it help is that I have created a task list tab and when selecting that tab I want to GoTo the latest actionable task. I understand what this is, I just can't reach it!
You set a string variable to the cell location, and then use GoTo with Reference - see example below:
Dim myCell As String
myCell = Range("A3").Value
Application.GoTo Reference:=Range(myCell)
The GoTo statement is used for branching in the code only. It doesn't interact with the cells at all. See the Microsoft docs here.
As findwindow says in the comments, you need to use the Range.select method. MSDN here
EDITED WITH PROGRESS
Dear Stackoverflow community,
I am working on a big excel file that does some calculations for me and my colleagues. Because the calculation data is a lot and is entered in Ranges (like "A1:H8"), not single cells (like "A1","C1",...), I want the users to be able to copy data from the same or another excel instance to my file.
The problem (edited):
The problem is, that just pasting cells formats the target cells (even if they are protected against formatting) and this has to be avoided. I searched through a lot of online discussions and finally made my own code, that allows me to copy and paste between two excel files in the same excel instance. Sadly, it does not work, if I copied the cells from another instance.
The code:
This is the code I use in "ThisWorkbook":
Sub PasteValuesOnly()
'if cells are pasted in named worksheets, only values are pasted
'is linked to Ctrl+V in options of macro menu
On Error GoTo err_handler
Dim Target As Range
Set Target = Selection
If Target.Parent.Name <> "Table1" Then
Selection.PasteSpecial
Else
Selection.PasteSpecial Paste:=xlPasteValues
End If
err_handler:
Exit Sub
End Sub
The system:
Windows 7
Excel 2010
What I tried besides my code (new progress):
As mentioned in the comments, I know Siddharth Rout's solution for only letting the users paste values, but I can't get it to work (not even in a fresh file when copying and pasting inside one Excel instance). I tried it for the whole workbook and for one single sheet.
What would help (edited):
It would be very helpful, if you could tell me how to optimize my code, so it works for two instances as well. If you know what is to do when I have an error with UndoList = Application.CommandBars(“Standard”).Controls(“&Undo”).List(1) in Siddharth Rout's solution with Excel 2010, this would be helpful, too.
Otherwise I would like every solution, that let's my users paste like they ever do, but prevent them from formatting the cells while pasting.
Thank you in advance
RaspiManu
After long hours of searching the internet, I found the solution of Donna Landy (Bella_Donna) in the microsoft forum. Her code is simple and works for CTRL+C / CTRL+V, Copy and Paste over Right Click Menu, Drag'n'Drop and even with two excel instances.
Because it starts on every single cell change and goes back to the cell or range that was changed, I slightly optimized it for my needs. Now, users that enter a list manually won't have to press "Enter" two times every time, they want to get to the next line below.
Assuming, the standard user will normally copy and paste, if there is a range of data, he or she does not want to retype, I changed the code, so the module sub only gets activated, if more than one cell has been changed (see below).
The solution:
In every worksheet, that has to be protected against formatting (modified):
Private Sub Worksheet_Change(ByVal Target As Range)
'activates format protection when changing a range
If Target.Cells.Count > 1 Then 'If more than one cell has been changed...
Call Worksheet_Change_Protected(Target) '...activating protection
End If
End Sub
In a module (unmodified):
Sub Worksheet_Change_Protected(ByVal Target As Range)
'Prevents user blithely obliterating in-cell formatting by undoing their paste and pasting the value
'Donna Landy 26.11.2018
'May be freely copied - hat tip appreciated :)
Dim SavedVal As Variant
On Error GoTo ErrHan
'Save the pasted value for later
SavedVal = Target.Value
'Switch off events to prevent infinite loop
Application.EnableEvents = False
'Undo the user's paste
Application.Undo
'Set target value
Target.Value = SavedVal
ErrExit:
'Remember to re-enable events
Application.EnableEvents = True
Exit Sub
ErrHan:
Resume ErrExit
End Sub
Thank you very much, Donna Landy!
I currently use a spreadsheet where I need to manually hyperlink 4 separate files in each row which include important information for referencing (3 are PDFs and 1 is an excel spreadsheet). Each row is full of information for a specific order number, which is conveniently part of each file that I need to hyperlink. Each of the 4 types of documents I would like to hyperlink into my excel sheet are also all packed into 4 folders path1, path2, path3, and path4, and they have their own column in the spreadsheet. Each folder will only contain one file with the order number.
I tried to automate this in excel only, using these formulas in the 4 columns:
K2 =IF(ISBLANK(C2)," ",HYPERLINK("J:path1\"&C2&".pdf",C2))
L2 =IF(ISBLANK(C2)," ",HYPERLINK("J:path2\"&C2&".pdf",C2))
M2 =IF(ISBLANK(C2)," ",HYPERLINK("J:path3\"&C2&".xlsx",C2))
N2 =IF(ISBLANK(C2)," ",HYPERLINK("J:path4\"&C2&".pdf",C2))
The formula references cell C2 which is the order number, and it fills the path with that number, which works great for the files which are consistently named. It also leaves the cell blank if there is no order number, because it happens sometimes and I need the function to not freak out when there is nothing there. The problem comes when I run into the file names that have other things tacked on the end such as a date. My formula is incapable of hyperlinking a file unless I give it the exact path to begin with.
I am wondering if anyone knows if excel is even capable of finding a file in a folder when only given part of the file name.
If there is not a way to do this in excel, I was hoping there may be a way to do this with VBA. I did some searching and found the Application.FileSearch feature in VBA, but it says "Object doesn't support this action." when I try to call it. (Which from a simple google search that seems to be the error due to Application.FileSearch not existing in excel 2007, but I am running 2013, so I'm not sure why this is happening)
I have a very novice understanding of VBA, so I am trying to slowly learn on the side. If anyone could help me come up with a code that would allow me to reference a cell, and find files containing that name so that I could print that path to a different cell, I would greatly appreciate your help.
Something like this should work (or at least point you down a path to investigate).
Sub HyperlinkFiles()
Dim strFile As String
strFile = Dir$("J:\path1\*" & Sheet1.Range("C2") & "*.pdf")
If (Len(strFile) > 1) Then
Sheet1.Range("k2").Hyperlinks.Add Sheet1.Range("k2"), strFile
Else
'No file was found that match so do nothing
'However, you could link to the folder to make manually searching easier
'Sheet1.Range("k2").Hyperlinks.Add Sheet1.Range("k2"), "J:\Path1"
End If
strFile = Dir$("J:\path2\*" & Sheet1.Range("C2") & "*.pdf")
If (Len(strFile) > 1) Then
Sheet1.Range("L2").Hyperlinks.Add Sheet1.Range("L2"), strFile
Else
'No file was found that match so do nothing
End If
strFile = Dir$("J:\path3\*" & Sheet1.Range("C2") & "*.xlsx")
If (Len(strFile) > 1) Then
Sheet1.Range("M2").Hyperlinks.Add Sheet1.Range("M2"), strFile
Else
'No file was found that match so do nothing
End If
End Sub
The caveat with this code is when there are 2 or more files that match the search pattern. For example, suppose cell C2 contains Stack and you have 2 files named stackoverflow.pdf and stackexchange.pdf. Which "stack" file do you want?
I have an Excel sheet that draws data from other, closed Excel workbooks. Currently it works fine when I list out the closed workbook's entire path, but I'd like to use a variable, stored in a separate cell, as part of the path name.
For example, I am trying to reference a workbook called
workbook12.10.12.xls
In a separate workbook (we'll say the "active" workbook), I have a cell with formula
=INDEX('C:\Path[workbook12.10.12.xls]SHEET1'!$B$1:$B$5, MATCH("match text", 'C:\Path[workbook12.10.12.xls]SHEET1'!$A$1:$A$5, 0))
which finds the value in workbook12.10.12's B column corresponding to the cell in the A column that contains "match text." This works fine; however, I have a cell in the active workbook with the value
12.10.12
and would like to somehow reference this value in the INDEX function.
I can't have the other workbooks open, so the INDIRECT function won't help. Googling seems to suggest that Excel doesn't have a simple one-stop solution for this kind of thing... can someone help please? Thanks!
From Frank Kabel's 2004 post at Dicks Blog you could
Use Laurent Longre has developed the free add-in MOREFUNC.XLL which includes the function INDIRECT.EXT
Use SQL.REQUEST as described here *does not appear to be supported anymore and I am not clear if this could handle your INDEX\MATCH request
Use Harlan Grove’s PULL function
In addition you could:
Create a "dirty link" directly via code that enters a formula referring to the workbook you need
For pulling values - but not for working with ranges - you could use Walkenbach's ExecuteExcel4Macro XLM method
I think what you what to do is to find the specific record in the specific file (date named).
You may do it by a simple VBA code.
Suppose you are going to search for a record# say REC001 in A1, date file 12.10.12 at cell C1, and have the result to be display at cell A7
On the worksheet you want to enter input and get output, rightclick the sheet tab and select 'View code' and paste the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("C1")) Is Nothing Then Exit Sub
Range("A7").Formula = "=INDEX('C:\TEMP\[workbook" & Range("C5").Value & ".xls]SHEET1'!$B$1:$B$5, MATCH(" & Range("A1").Value & ", 'C:\TEMP\[workbook" & Range("C5").Value & ".xls]SHEET1'!$A$1:$A$5, 0))"
End Sub
Then every time you edit C1, the formula will be updated.
Actually I don't think you should use INDEX function in your case. It is more simple to use a VLOOKUP. E.g.:
Range("A8").Formula = "=vlookup(" & Range("A1").Value & ",'C:\TEMP\[workbook" & Range("C5").Value & ".xls]SHEET1'!$A$1:$B$5,2,false)"
You will have to note on a few points:
1. you paste the code on the Sheet1 object (or the sheet name) but not to insert a new module
2. your path and filename for the target file is correct, including the .xls and .xlsx
3. your original file only cover to $B$5
4. on VBA, recommend you to save the file as .xlsm format
You can store a full reference including the file path to a range in a closed file in a name in excel (either directly or via VBA based on selections in different cells and using the Worksheet_Change procedure as above) and then refer to the file using the name in a formula as normal. This gets over the limitation in the INDIRECT function.
The VBA is very simple:
New_Ref = Sheets("Wells").Range("K6")
ActiveWorkbook.Names("MyWorkbook").RefersTo = "=" & New_Ref
The only trick is to be sure to include "=" in the name.
Names have a huge number of uses once you spot this. I have used this to get data from a closed file on a remote sharepoint site without any difficulty - I assume sharepoint deals with all the permissions.