0

我有一个包含许多产品图片的文件夹。每个产品有多个图像。我需要识别以我的产品编号(例如,100100)开头并以两个结尾“_FRONT”或“_ALTERNATE”之一结尾的那些。这两者之间还有其他信息。例如,文件名可以是 100100_headset_FRONT 或 100100_headset_SIDE。我希望它找到每个产品的正面或替代图像。

我已经成功地提取了图像,并且我认为我已经接近命名文件的方式,但并不完全在那里。代码返回错误“找不到指定的文件”

Sub PictureP()
Dim picname As String, picend As String
Dim PicPath As String
Dim lThisRow As Long
Dim Pic As Shape
Dim rngPic As Range


lThisRow = 3

Do While (Cells(lThisRow, 2) <> "")

    Set rngPic = Cells(lThisRow, 1) 'This is where picture will be inserted

    picname = Cells(lThisRow, 2) 'This is the picture name
    picend = "_FRONT"

    present = Dir("H:\Media\Images\1 Web Ready\Previews\" & picname & "*" & picend & ".jpg")
    PicPath = ("H:\Media\Images\1 Web Ready\Previews\" & picname & "*" & picend & ".jpg")


If present <> "" Then

      Set Pic = ActiveSheet.Shapes.AddPicture(PicPath, msoFalse, msoCTrue, 1, 1, -1, -1)

    Else

    Cells(lThisRow, 1) = ""

    End If

lThisRow = lThisRow + 1
Loop

Range("B3").Select
On Error GoTo 0
Application.ScreenUpdating = True

Exit Sub

End Sub

代码返回错误“找不到指定的文件”

4

1 回答 1

1

Dir()正在正确评估*通配符并返回匹配的 FIRST 值。

PicPath =正在设置一个字符串值。设置字符串值不关心通配符,因此它被添加为文字值。

如果您在运行时调试并打印出这两个值,您会*在 PicPath 中看到 。

最简单的解决方案是更改 picPath 以使用 的结果Dirpresent并将其附加到Dir()搜索的目录。

见下文。

Sub PictureP()
Dim picname As String, picend As String
Dim PicPath As String
Dim lThisRow As Long
Dim Pic As Shape
Dim rngPic As Range


lThisRow = 3

Do While (Cells(lThisRow, 2) <> "")

    Set rngPic = Cells(lThisRow, 1) 'This is where picture will be inserted

    picname = Cells(lThisRow, 2) 'This is the picture name
    picend = "_FRONT"

    present = Dir("H:\Media\Images\1 Web Ready\Previews\" & picname & "*" & picend & ".jpg")
    PicPath = ("H:\Media\Images\1 Web Ready\Previews\" & present)


If present <> "" Then

      Set Pic = ActiveSheet.Shapes.AddPicture(PicPath, msoFalse, msoCTrue, 1, 1, -1, -1)

    Else

    Cells(lThisRow, 1) = ""

    End If

lThisRow = lThisRow + 1
Loop

Range("B3").Select
On Error GoTo 0
Application.ScreenUpdating = True

Exit Sub

End Sub
于 2019-07-11T14:59:46.583 回答