正如问题所述,我制作了一个简单的宏,该宏接受几张数据并将其转换为图表。当我通过电子邮件向老板发送包含宏的工作簿时,marco可以在我的笔记本电脑上完美工作。如果我没记错的话,它抛出了错误42或类似的东西。
代码中突出显示的行是设置图形标题的行。我提供了一个函数,该函数从通过For循环遍历的数组创建图形标题。一旦我将其更改为其他文本值并取出数组即可。
控制宏的按钮
Private Sub CommandButton1_Click()
Dim selectedWorksheet As Worksheet
Dim numItems As Integer
Dim numOfIdentifiers As Integer
Dim identArray() As String
Dim itemsFoundL() As String
Dim itemsSoldL() As Integer
Dim identifiers As Range
Dim ident As Range
Dim upperBound As String
Dim lowerBound As String
Dim foodLBound As String
Dim foodUBound As String
Dim nonFoodLBound As String
Dim nonFoodUBound As String
Dim foodNameColumn As String
Dim foodSoldColumn As String
Dim nonFoodNameColumn As String
Dim nonFoodSoldColumn As String
Dim sheetName As Range
Dim i As Integer
upperBound = Range("J1").Value
lowerBound = Range("I1").Value
foodLBound = Range("I3").Value
foodUBound = Range("J3").Value
nonFoodLBound = Range("I4").Value
nonFoodUBound = Range("J4").Value
foodNameColumn = Range("I5").Value
foodSoldColumn = Range("I6").Value
nonFoodNameColumn = Range("I8").Value
nonFoodSoldColumn = Range("I9").Value
Set sheetName = Range("I2")
Set identifiers = Range(lowerBound, upperBound)
Set selectedWorksheet = ActiveWorkbook.Worksheets(CStr(sheetName))
numOfIdentifiers = identifiers.Count
ReDim identArray(0 To numOfIdentifiers - 1)
i = 0
For Each ident In identifiers
identArray(i) = ident.Value
i = i + 1
Next ident
For i = 0 To numOfIdentifiers - 1
numItems = CInt(numberOfItems(selectedWorksheet, identArray(i), foodLBound, foodUBound))
If numItems = 0 Then
numItems = CInt(numberOfItems(selectedWorksheet, identArray(i), nonFoodLBound, nonFoodUBound))
numItems = numItems - 1
ReDim itemsFoundL(0 To numItems)
ReDim itemsSoldL(0 To numItems)
itemsFoundL = itemsFound(selectedWorksheet, identArray(i), nonFoodLBound, nonFoodUBound, numItems, nonFoodNameColumn)
itemsSoldL = itemsSoldFound(selectedWorksheet, identArray(i), nonFoodLBound, nonFoodUBound, numItems, nonFoodSoldColumn)
Else
numItems = numItems - 1
ReDim itemsFoundL(0 To numItems)
ReDim itemsSoldL(0 To numItems)
itemsFoundL = itemsFound(selectedWorksheet, identArray(i), foodLBound, foodUBound, numItems, foodNameColumn)
itemsSoldL = itemsSoldFound(selectedWorksheet, identArray(i), foodLBound, foodUBound, numItems, foodSoldColumn)
End If
Call CreateCharts(itemsFoundL, itemsSoldL, identArray(i), numItems)
Next i
End Sub
图表创建助手功能
Function CreateCharts(items As Variant, itemsSold As Variant, chartTitle As String, itemCount As Integer)
If itemCount > 0 Then
Charts.Add
ActiveChart.ChartType = xlBarStacked
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).XValues = items
ActiveChart.SeriesCollection(1).Values = itemsSold
ActiveChart.ChartArea.Format.TextFrame2.TextRange.Font.Name = "Arial"
With ActiveChart
.HasLegend = False
.HasTitle = True
.chartTitle.Text = chartTitle
End With
Else
End If
End Function