对象变量或未设置块变量(错误91)错误

时间:2015-11-25 17:37:22

标签: excel vba excel-vba

我有以下代码,但现在显示错误:

Sub AttachLabelsToPoints()

   'Dimension variables.
   Dim Counter As Integer
   Dim ChartName As String
   Dim xVals As String

   ' Disable screen updating while the subroutine is run.
   Application.ScreenUpdating = False

   'Store the formula for the first series in "xVals".
   xVals = ActiveChart.SeriesCollection(1).Formula

   'Extract the range for the data from xVals.
   xVals = Mid(xVals, InStr(InStr(xVals, ","), xVals, _
      Mid(Left(xVals, InStr(xVals, "!") - 1), 9)))
   xVals = Left(xVals, InStr(InStr(xVals, "!"), xVals, ",") - 1)
   Do While Left(xVals, 1) = ","
      xVals = Mid(xVals, 2)
   Loop

   'Attach a label to each data point in the chart.
   For Counter = 1 To Range(xVals).Cells.Count
     ActiveChart.SeriesCollection(1).Points(Counter).HasDataLabel = _
         True
     ActiveChart.SeriesCollection(1).Points(Counter).DataLabel.Text = _
     Range(xVals).Cells(Counter, 1).Offset(0, -1).Value
   Next Counter

End Sub

错误特别围绕xVals = ActiveChart.SeriesCollection(1).Formula语句。当我在它前面放一个Set时,它只是要求一个物体。

有人能帮助我解决错误吗?

1 个答案:

答案 0 :(得分:1)

确保您要使用的图表是工作表上处于活动状态的实际图表。

在设置'xVals`之前放置此代码并根据需要进行调整。

private void checkConditions(JFormattedTextField fieldA, JFormattedTextField fieldB) {
    // Make sure something is contained within fieldA and 
    // that it's actually numerical text.
    if(!fieldA.getText().isEmpty() && 
                fieldA.getText().matches("([-]?)\\d+([,]\\d+)?(([.]\\d+)?)")) {
        // Convert the supplied text to Double and
        // ensure the desired numerical formating.
        String res = (String)tausenderPunkt(Double.parseDouble(fieldA.getText().replace(",","")));
        fieldA.setText(res);
        // Set Focus to our next text fieldB.
        fieldB.requestFocusInWindow();
        // Highlight the contents (if any) within the
        // next text fieldB.
        fieldB.selectAll();
    }
    // If fieldA is empty or fieldA does not contain 
    // numerical text then inform User and re-highlight
    // the entry in fieldA.
    else {
        JOptionPane.showMessageDialog (null, "Please Enter Numerical Values Only!", 
                "Incorrect Entry", JOptionPane.WARNING_MESSAGE);
        fieldA.selectAll();
    }
}

一般来说,使用Dim c As ChartObject Set c = Sheets("Sheet6").ChartObjects("Chart 1") 'change to your chart name c.Activate 'Store the formula for the first series in "xVals". xVals = ActiveChart.SeriesCollection(1).Formula 任何东西(图表/表格/单元格等)是不好的做法,但在操作图表时,这是AFAIK的唯一方法。我不知道以这种方式直接使用对象的方法。如果其他人这样做,也许他们可以发布更好的答案。