我想让这段代码从单元格中的值中保存图像名称。例如,如果“cat”在单元格Y36中,我希望它被称为cat.jpg。
如果我没有& FileNumber &
或FileNumber = Range("Y36")
,则以下代码有效。
Sub ExportCellsAsPicture()
FileNumber = Range("Y36")
Const FName As String = "HD:Users:User:Desktop:" & FileNumber & ".jpg"
Dim pic_rng As Range
Dim ShTemp As Worksheet
Dim ChTemp As Chart
Dim PicTemp As Picture
Application.ScreenUpdating = False
Set pic_rng = Worksheets("QR Code").Range("Y50:AS70") 'Set your range here
Set ShTemp = Worksheets.Add
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=ShTemp.Name
Set ChTemp = ActiveChart
pic_rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
ChTemp.Paste
Set PicTemp = Selection
With ChTemp.Parent
.Width = PicTemp.Width + 10
.Height = PicTemp.Height + 10
End With
ChTemp.Export Filename:="HD:Users:User:Desktop:" & FileNumber & ".jpg", FilterName:="jpg"
Application.DisplayAlerts = False
ShTemp.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
更新:工作代码
Sub whatsup()
Dim pic_rng As Range
Dim ShTemp As Worksheet
Dim ChTemp As Chart
Dim PicTemp As Picture
Dim fileCon As String
fileCon = "JK"
Application.ScreenUpdating = False
Set pic_rng = Worksheets("QR Code").Range("Y50:AS70") 'Set your range here
Set ShTemp = Worksheets.Add
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=ShTemp.Name
Set ChTemp = ActiveChart
pic_rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
ChTemp.Paste
Set PicTemp = Selection
With ChTemp.Parent
.Width = PicTemp.Width + 8
.Height = PicTemp.Height + 8
End With
'Here I want the .jpg to be called test_yyyy_mm_dd.jpg
ChTemp.Export Filename:="HD:Users:User1:Desktop:" & fileCon & ".jpg"
Application.DisplayAlerts = False
ShTemp.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:0)
将Const更改为变量。根据定义,Const(ant)不能改变,但你使用它就像一个变量。将其更改为以下两行:
Dim FName As String
FName = "HD:Users:User:Desktop:" & FileNumber & ".jpg"
您还应该在设置之前声明FileNumber。
Dim FileNumber As Long 'if this is a number. If not, string
FileNumber = Range("Y36")
最后,使所有内容显式和编译总是好的,以确保至少你的语法是正确的。这将有助于减少许多简单但容易错过的错误。将它放在模块的最顶层:
Option Explicit
然后在调试之前编译并更正任何语法错误。
要进行调试,请在第一个可执行行(而不是Dim语句)上设置断点,然后逐行检查以确定它是否按预期工作。