如何检查Excel工作表上是否已有对象,如果没有,则插入文件?

时间:2016-09-29 15:18:16

标签: excel vba excel-vba

此代码块打开选择文件窗口,然后将文件包含在工作表中。问题在于你可以做多少次没有限制。如何执行检查并阻止它包含多个文件?

Public Sub insertFile()

'Select the cell in which you want to place the attachment
Range("F92").Select

'Get file path
fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
If LCase(fpath) = "false" Then Exit Sub

'Insert file
ActiveSheet.OLEObjects.Add _
Filename:=fpath, _
Link:=False, _
DisplayAsIcon:=True, _
IconFileName:="excel.exe", _
IconIndex:=0, _
IconLabel:=extractFileName(fpath)

End Sub
Public Function extractFileName(filePath)

    For i = Len(filePath) To 1 Step -1
        If Mid(filePath, i, 1) = "\" Then
        extractFileName = Mid(filePath, i + 1, Len(filePath) - i + 1)
        Exit Function
        End If
Next

End Function

1 个答案:

答案 0 :(得分:0)

如何简单

If ActiveSheet.OLEObjects.Count > 0 Then Exit Sub

sub开头?