excel vba自动图片导入

2024-12-14 05:21:57
推荐回答(4个)
回答1:

假设图片放在D盘根目录名为test的文件夹中,则可使用下列VBA代码自动插入图片:
Sub Insertpic()
Shell ("cmd /c dir ""D:\test"" /a:-d /b >""D:\2888.txt")
Application.Wait (Now + TimeValue("0:00:01"))

Sheet2.Select
With ActiveSheet.QueryTables.Add(Connection:="TEXT;D:\2888.txt", _
Destination:=Range("$A$1"))
.Name = "1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 936
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
d = Sheet2.Range("A10000").End(xlUp).Row

a = Sheet2.Cells(1, 1)
Sheet3.Select
ActiveSheet.Pictures.Insert ("D:\test\" & a)
b = ActiveSheet.Shapes(1).Width
c = ActiveSheet.Shapes(1).Height

m = Sheet1.Range("A1").Width / Sheet1.Columns(1).ColumnWidth
n = b / m
Sheet1.Columns("A:A").ColumnWidth = n
m = Sheet1.Range("A1").Width / Sheet1.Columns(1).ColumnWidth
n = b / m
Sheet1.Columns("A:A").ColumnWidth = n
m = Sheet1.Range("A1").Width / Sheet1.Columns(1).ColumnWidth
n = b / m
Sheet1.Columns("A:Z").ColumnWidth = n
Sheet1.Rows("1:10000").RowHeight = c

e = Int(960 / b)

For i = 1 To d
f = Int(i / e) + 1
If f = Int((i - 1) / e) + 2 Then
f = f - 1
End If
g = i Mod e
If g = 0 Then
g = e
End If
a = Sheet2.Cells(i, 1)
Sheet1.Shapes.AddPicture _
"D:\test\" & a, _
True, True, (g - 1) * b, (f - 1) * c, b, c
Next i

Sheet1.Select
End Sub
说明:1.上述代码可自动识别图片名称及图片尺寸,自动识别图片数量等;
2.必须以管理员账户登录电脑,才能成功执行上述代码;
3.需要放到"thisworkbook"的VBA编辑框才能运行;
4.执行该代码会在D盘根目录中生成一个名为2888的txt格式文件,运行完成后,可删除该文件;
5.每张图片尺寸不能超过320*546像素,若超过,则不能成功执行代码,可将图片文件夹的图片按名称排序后,将第一张图片的尺寸改小到上述尺寸以内,再执行代码;
6.图片数量超过10000张时,上述代码需要做适当修改。

回答2:

可以用vba完成.
假设图片名称在A列,图片放在当前文件所在文件夹下的\pic\目录,且格式均为jpg.
运行下面的代码可以根据A列名称将相应的图片插入到对应行的b列位置,且调整大小恰好与其所在单元格一致.

按住alt,依次按f11,i,m
粘贴代码后按f5

Sub test()
p = ThisWorkbook.Path & "\pic\"
For r = 2 To Range("a65536").End(xlUp).Row
With Cells(r, 2)
ActiveSheet.Shapes.AddPicture(p & Cells(r, 1) & ".jpg", 0, 1, .Left, .Top, .Width, .Height).Placement = xlMoveAndSize
End With
Next
End Sub

回答3:

假设图片有100张,图片格式为“.jpg",图片放在”D:\PICTURE“中,要放入图片的名称写在A1到A100中(不含后缀名),图片插入到B1到B100的单元格。代码如下:

Sub 插入图片()
Dim I As Integer
For I = 1 To 100
Cells(I, 2).Select
ActiveSheet.Pictures.Insert "D:\PICTURE\" & Cells(I, 1) & ".jpg"
Next I
End Sub

回答4:

很简单!