我正在开发一个excel宏,当一个部件号被扫描到电子表格中时(在A栏中),它会自动打开一个与该部件号相关的PDF文档。我已经让它适用于我想要看的第一个单元格,但在那之后就被卡住了。我可以添加一堆“if”语句,但必须有一种方法来清理它,而不是有数百个“if”语句。我需要从单元格A9开始并继续到单元格A209。以下是我到目前为止的情况。将这些组合成更简单的代码的任何帮助将不胜感激。提前谢谢!
Private Sub Worksheet_Change(ByVal Target As Range)
Dim varCellvalue As String
If Target.Address = "$A$9" Then
varCellvalue = Range("A9").Value
ThisWorkbook.FollowHyperlink "F:\ITEM PART MASTER\" & varCellvalue & "\" & varCellvalue & " Pack.pdf"
End If
If Target.Address = "$A$10" Then
varCellvalue = Range("A10").Value
ThisWorkbook.FollowHyperlink "F:\ITEM PART MASTER\" & varCellvalue & "\" & varCellvalue & " Pack.pdf"
End If
If Target.Address = "$A$11" Then
varCellvalue = Range("A11").Value
ThisWorkbook.FollowHyperlink "F:\ITEM PART MASTER\" & varCellvalue & "\" & varCellvalue & " Pack.pdf"
End If
这可以继续下去,但我认为必须有一种更有效的方法将这些组合成一个简单的陈述。
答案 0 :(得分:1)
使用您的代码,您所需要的只是非常简单和简短(见下面的代码)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim varCellvalue As String
' run your code only if a cell inside the Range("A9:A11") has been changed
If Not Intersect(Target, Range("A9:A11")) Is Nothing Then
varCellvalue = Target.Value
ThisWorkbook.FollowHyperlink "F:\ITEM PART MASTER\" & varCellvalue & "\" & varCellvalue & " Pack.pdf"
End If
End Sub
答案 1 :(得分:0)
您可以使用Select Case
代替
Private Sub Worksheet_Change(ByVal Target As Range)
Dim varCellvalue As String
Select Case Target.Address
Case "$A$9"
varCellvalue = Range("A9")
Case "$A$10"
varCellvalue = Range("A10")
Case "$A$11"
varCellvalue = Range("A11")
End Select
ThisWorkbook.FollowHyperlink "F:\ITEM PART MASTER\" & varCellvalue & "\" & varCellvalue & " Pack.pdf"
或者你可以更快地完成它,因为你只是将Target的值插入到url中。
Private Sub Worksheet_Change(ByVal Target As Range)
ThisWorkbook.FollowHyperlink "F:\ITEM PART MASTER\" & Target & "\" & Target & " Pack.pdf"
答案 2 :(得分:0)
如果你需要将它限制为几个单元格,而不是每个范围,那么你可以使用一个数组加载目标单元格,只需检查目标地址是否在那里,然后运行你的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim varCellvalue As String
Dim targetCells() As Variant
targetCells() = Array("$A$9", "$A$10", "$A$11")
If (UBound(Filter(targetCells, Target.Address)) > -1) Then
'This cell is in your array
Debug.Print Target.Value
ThisWorkbook.FollowHyperlink "F:\ITEM PART MASTER\" & Target.Value & "\" & Target.Value & " Pack.pdf"
End If
End Sub