我正在尝试创建一个将通过以下代码通过电子邮件发送工作表的一部分的功能:
Function PictureToHTML(wbk, Namesheet, nameRange, imgFile)
wbk.Activate
Worksheets(Namesheet).Activate
nameRange = "C7:C10"
Set Plage = wbk.Worksheets(Namesheet).Range(nameRange)
Plage.CopyPicture
TempFilePath = Environ$("temp") & "\" & imgFile
Set newchart = wbk.Worksheets(Namesheet).ChartObjects.Add(Plage.Left, Plage.Top, Plage.Width, Plage.Height)
With newchart
.Activate
.Chart.parent.Border.LineStyle = 0
.Chart.Paste
.Chart.Export TempFilePath, "PNG"
End With
Worksheets(Namesheet).ChartObjects(Worksheets(Namesheet).ChartObjects.Count).Delete
Set Plage = Nothing
PictureToHTML = "<br><B>" & Namesheet & ":</B><br>" _
& "<img src='cid:" & imgFile & "'>"
End Function
我暂时对要剪切的范围进行了硬编码(即使这不应该成为问题...),但在此行出现错误:
Set newchart = wbk.Worksheets(Namesheet).ChartObjects.Add(Plage.Left, Plage.Top, Plage.Width, Plage.Height)
完整错误:
运行时错误'-2147417878(80010108)': 对象“ ChartObjects”的方法“添加”失败
谁能告诉我我的错误在哪里? 更新的代码:
Function PictureToHTML(wbk, Namesheet, nameRange, imgFile)
Dim WeightsSheet As Worksheet
Dim newChart As ChartObject
wbk.Activate
Set WeightsSheet = wbk.Worksheets(Namesheet)
Set Plage = wbk.Worksheets(Namesheet).Range(nameRange)
Plage.CopyPicture
TempFilePath = Environ$("temp") & "\" & imgFile
Set newChart = WeightsSheet.ChartObjects.Add(Plage.Left, Plage.Top, Plage.Width, Plage.Height)
With newChart
.Activate
.Chart.parent.Border.LineStyle = 0
.Chart.Paste
.Chart.Export TempFilePath, "PNG"
End With
WeightsSheet.ChartObjects(WeightsSheet.ChartObjects.Count).Delete
Set Plage = Nothing
PictureToHTML = "<br><B>" & Namesheet & ":</B><br>" _
& "<img src='cid:" & imgFile & "'>"
End Function
答案 0 :(得分:1)
未明确声明变量。尽管这里应该没有问题,但是由于应该将newChart
视为Variant
,因此请尝试在Dim newChart as ChartObject
之前的行上写wbk.Activate
。
然后分别调用像这个小东西一样的东西:
Sub TestMe()
Dim newChart As ChartObject
Set newChart = Worksheets(1).ChartObjects.Add(100, 100, 100, 100)
End Sub
然后开始添加Plage.Left, Plage.Top, Plage.Width, Plage.Height
而不是硬编码参数(100)。然后也添加wbk.Worksheets(Namesheet)
,看看它是否有效。
不声明变量确实是一个坏习惯。如果您全部声明,则此方法有效。在这个特定的小示例中,问题是nameRange
变量:
Option Explicit
Sub TestMe()
Debug.Print PictureToHTML(ThisWorkbook, "Sheet1", Range("A1:E20"), "probably.png")
End Sub
Function PictureToHTML(wbk As Workbook, Namesheet As String, _
nameRange As Range, imgFile As String) As String
Dim WeightsSheet As Worksheet
Dim newChart As ChartObject
Dim Plage As Range
Dim tempFilePath As String
Set WeightsSheet = wbk.Worksheets(Namesheet)
Set Plage = wbk.Worksheets(Namesheet).Range(nameRange.Address)
Plage.CopyPicture
tempFilePath = Environ$("temp") & "\" & imgFile
Set newChart = WeightsSheet.ChartObjects.Add( _
Plage.Left, Plage.Top, Plage.Width, Plage.Height)
With newChart
.Chart.Parent.Border.LineStyle = 0
.Chart.Paste
.Chart.Export tempFilePath, "PNG"
End With
WeightsSheet.ChartObjects(WeightsSheet.ChartObjects.Count).Delete
PictureToHTML = "<br><B>" & Namesheet & ":</B><br>" & "<img src='cid:" & imgFile & "'>"
End Function
下一步,请考虑阅读Option Explicit的文档: