我试图将工作簿中的引号名称超链接到文件的位置。并非所有文件都存在,我想在创建超链接之前测试一个布尔值以查看它们是否存在。我一直在使用活动单元格中的文件名来保留字符串和搜索。命名约定是' XX-MMDDYY.XX。保存的文件名为Quote_XX-MMDDYY.XX。我结合了#34;引用_"用活动单元格来搜索文件,但我的宏似乎只循环遍历列表。
Sub LoopRange()
Dim currRow As Integer, lastRow As Integer
Dim ws As String, quoteID As String
Dim path As String
Dim FileName As String
path = "C:\Some file path\"
ws = "Quote LOG"
currRow = 3
lastRow = Sheets(ws).Cells(Sheets(ws).Rows.Count, "A").End(xlUp).Row
While currRow <= lastRow
Sheets(ws).Cells(currRow, 1).Select
quoteID = "Quote_" & ActiveCell.value
FileName = path & quoteID
If Dir(FileName) <> "" And quoteID <> "" Then
Sheets(ws).Hyperlinks.Add anchor:=Cells(currRow, 2), Address:=FileName, TextToDisplay:=quoteID
End If
currRow = currRow + 1
Wend
End Sub
答案 0 :(得分:0)
MacroMan的提示有帮助吗?如果没有,请告诉我,我会采取行动。
但是,对VBA来说非常好的一件事就是如何(避免.Activate和.Select)[How to avoid using Select in Excel VBA macros。考虑到这一点,我已经调整了你的代码,它应该运行得更顺畅:
Sub LoopRange()
Dim currRow As Integer, lastRow As Integer
Dim ws As String, quoteID As String
Dim path As String
Dim FileName As String
Dim cellValue As String
path = "C:\Some file path\"
ws = "Quote LOG"
currRow = 3
lastRow = Sheets(ws).Cells(Sheets(ws).Rows.Count, "A").End(xlUp).Row
While currRow <= lastRow
'Sheets(ws).Cells(currRow, 1).Select
cellValue = Sheets(ws).Cells(currRow, 1)
'quoteID = "Quote_" & ActiveCell.Value
quoteID = "Quote_" & Sheets(ws).Cells(currRow, 1)
Debug.Print quoteID
FileName = path & quoteID & ".pdf"
If Dir(FileName) <> "" And quoteID <> "" Then
Sheets(ws).Hyperlinks.Add anchor:=Cells(currRow, 2), Address:=FileName, TextToDisplay:=quoteID
End If
currRow = currRow + 1
Wend
End Sub
答案 1 :(得分:0)
我的文件名与代码不匹配。我需要将“Quote_”添加到quoteID和文件类型,在本例中为“.pdf”添加到FileName
** Sub LoopRange()
Dim currRow As Integer, lastRow As Integer
Dim ws As String, quoteID As String
Dim path As String
Dim FileName As String
path = "C:\Users\pxbotr\Documents\Quote DataBase\"
ws = "Quote LOG"
currRow = 3
lastRow = Sheets(ws).Cells(Sheets(ws).Rows.Count, "A").End(xlUp).Row
While currRow <= lastRow
Sheets(ws).Cells(currRow, 1).Select
quoteID = "Quote_" & ActiveCell.Value
FileName = path & quoteID & ".pdf"
If Dir(FileName) <> "" And quoteID <> "" Then
Sheets(ws).Hyperlinks.Add anchor:=Cells(currRow, 1), Address:=FileName, TextToDisplay:=quoteID
End If
currRow = currRow + 1
Wend
End Sub
**