问题
That's right. If I change the 'C' in 'Chart_Series_W_Gain_AAPL' in the following code to any other letter the code works. Otherwise it throws an Error 1004 at the Series.Formula assignment. In fact, if I use any random name that begins with 'c' the code fails but not otherwise. I've tried closing Excel and reopening, but same issue. I came across this because I had been naming my chart series defined names beginning with the name of the chart, but then I decided that was confusing and I attempted to prepend defined name used as a chart series with "Chart_Series_". Pretty benign change, one would think.
Dim objChartWGain As Chart
Dim objSeries As Series
Set objChartWGain = Charts("W Gain")
Set objSeries = objChartWGain.SeriesCollection.NewSeries
ActiveWorkbook.Names.Add "Chart_Series_W_Gain_AAPL", "=W_Gain_Data_Array(W_Gain_Data_Alloc,1,W_Gain_Data_GainLossCurr)"
objSeries.Formula = "=SERIES(""AAPL"",,'ThomTrade-charts.xlsb'!Chart_Series_W_Gain_AAPL,1)"
回答1:
MSDN indicates you can't use the letters "C" or "R" (upper/lower) as names. I think there is a bug relating to when this letter is the first letter in the Name is either R or C (or r or c) which I have replicated your error.
Try using the Name's address in a string concatenated to your formula, like so:
Sub ChtSeries()
Dim objChartWGain As Chart
Dim objSeries As Series
Dim nmAddress As String
Dim n As Name
Set objChartWGain = Charts("W Gain")
'Replace with your Name definition:'
Set n = ActiveWorkbook.Names.Add("Chart_Series_W_Gain_AAPL", Sheets("Sheet2").Range("A2:A4"))
'Turn the Name's address in to a usable string:'
nmAddress = Replace(n.RefersTo, "=", vbNullString)
Set objSeries = objChartWGain.SeriesCollection(1)
objSeries.Formula = "=SERIES(""AAPL"",," & nmAddress & ",1)"
End Sub
Info from MSDN here:
http://office.microsoft.com/en-us/excel-help/define-and-use-names-in-formulas-HA102749565.aspx#_Learn_about_syntax
You cannot use the uppercase and lowercase characters "C", "c", "R", or "r" as a defined name, because they are all used as a shorthand for selecting a row or column for the currently selected cell when you enter them in a Name or Go To text box.
来源:https://stackoverflow.com/questions/16002425/excel-vba-runtime-error-1004-only-with-names-that-begin-with-c