我试图获取图片文件的尺寸。所有路径都列在excel列中,希望使用文件维度填充另一列。我的尝试得到了错误
运行时错误' 91':对象变量或未设置块变量
就行了
Set objfile = objfolder.parsename(filename)
欢迎任何和所有帮助......我是初学者。
Private Sub CommandButton1_Click()
Dim objShell As Object
Dim objFolder As Object
Dim objFile As Object
Dim filepath As String
Dim filename As String
Dim filedimensions As String
Dim prefilename As Integer
Dim folderpath As String
Dim i As Integer
i = 7
filepath = Worksheets("Sheet1").Cells(i, 1).Value
Do Until IsEmpty(filepath)
filepath = Worksheets("Sheet1").Cells(i, 1).Value
prefilename = InStrRev(filepath, "\")
folderpath = Left(Worksheets("Sheet1").Cells(i, 1).Value, prefilename)
filename = Right(filepath, Len(filepath) - prefilename)
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(folderpath)
Set objFile = objFolder.ParseName(filename)
filedimensions = objFile.ExtendedProperty("Dimensions")
Worksheets("Sheet1").Cells(i, 17).Value = filename
Worksheets("Sheet1").Cells(i, 21).Value = filedimensions
i = i + 1
Loop
End Sub
答案 0 :(得分:2)
此错误表示您尝试使用的对象包含VBA用语中的Nothing。
了解出现错误的行,查看您尝试使用的对象:objFolder
。 objFolder
在哪里分配?就在上面就行了。为什么没有分配别的东西而不是什么?因为objShell.Namespace
没有返回任何内容。为什么objShell.Namespace
没有返回?因为该文件夹不存在。
您的代码中有一些修改可以帮助您解决问题。正如@braX F8
所提到的,立即窗口(Ctrl + G)加上断点可以创造奇迹。
Private Sub CommandButton1_Click()
Dim objShell As Object
Dim objFolder As Object
Dim objFile As Object
Dim filepath As String
Dim filename As String
Dim filedimensions As String
Dim prefilename As Integer
Dim folderpath As String
Dim i As Integer
'Moved this line out of the loop; assigning once is enough.
Set objShell = CreateObject("Shell.Application")
i = 7
filepath = Worksheets("Sheet1").Cells(i, 1).Value
Do Until IsEmpty(filepath)
filepath = Worksheets("Sheet1").Cells(i, 1).Value
prefilename = InStrRev(filepath, "\")
folderpath = Left(Worksheets("Sheet1").Cells(i, 1).Value, prefilename)
filename = Right(filepath, Len(filepath) - prefilename)
Set objFolder = objShell.Namespace(folderpath)
'Check whether objFolder resolved to something.
If objFolder Is Nothing Then
MsgBox "Folder not found: " & folderpath, vbInformation + vbOKOnly, "Note"
Else
Set objFile = objFolder.ParseName(filename)
filedimensions = objFile.ExtendedProperty("Dimensions")
Worksheets("Sheet1").Cells(i, 17).Value = filename
Worksheets("Sheet1").Cells(i, 21).Value = filedimensions
End If
i = i + 1
Loop
End Sub