passing loop variable in vba to ActiveChart.SetSourceData Source:=Range[...] - excel

I've problems passing variable i into a loop that selects chart source values.
Sub Macro()
For i = 2 To 10
Windows("Book1").Activate
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$F$1,Sheet1!$A$2:$F$2" _
)
Next i
End Sub
I want to change the series value Sheet1!$A$2:$F$2" and put i value there -> Sheet1!$A$i:$F$i"
I tried different approaches, but they didn't work
How to loop Ranges in VBA?
Excel vba Charting, editting the range
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$F$1,("Sheet1!$A$" & i & ":$F$" & i)" _

Okay, I found a workaround to my problem with selecting a value range differently.
Code below worked:
For i = 2 To 10
newName = "=Sheet1!$A$" + CStr(i)
newValues = "=Sheet1!$B$" + CStr(i) + ":$F$" + CStr(i)
ActiveChart.FullSeriesCollection(1).Name = newName
ActiveChart.FullSeriesCollection(1).Values = newValues
Next i

You have some unneeded quotes:
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$F$1,Sheet1!$A$" & i & ":$F$" & i)

Don't remember to assign i to str value
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$F$1,Sheet1!$A$" + cstr(i) + ":$F$" + cstr(i)
And the better way is createa variable
distinctrange = "Sheet1!$A$1:$F$1,Sheet1!$A$" + cstr(i) + ":$F$" + cstr(i)
ActiveChart.SetSourceData Source:=Range(distinctrange)

Related

Run time error 1004 when trying to input hyperlinks into cells

I seem to have no problem adding a hyperlink into one cell but when I try and add into multiple cells there is a problem. I have also tried using .formula method and writing out the =HYPERLINK formula but that encountered the same issue... any help would be greatly appreciated!
With Sheets(sheetName)
.Hyperlinks.Add Anchor:=.Range("B1"), _
Address:=folderName, _
TextToDisplay:="Client"
End With
For i = 0 To lastRow - 2
If reportRequired(i) = "Yes" Then
fileName = folderName + "\" + clients(i) + ".docx"
With Sheets(sheetName)
.Hyperlinks.Add Anchor:=.Range(Cells(i + 2, 2)), _
Address:=fileName, _
TextToDisplay:=clients(i)
End With
End If
Next i
Using the hyperlink formula I tried this way as well:
For i = 0 To lastRow - 2
If reportRequired(i) = "Yes" Then
fileName = folderName + "\" + clients(i) + ".docx"
Sheets(sheetName).Range(Cells(i + 2, 2)).formula = "=HYPERLINK(" + fileName + """ + clients(i) + """ + ")"
End If
Next i

Excel VBA can't save file

This is my code but I have a problem saving a file.
Private o As Integer
Public Sub Procedure1()
o = 1
End Sub
Sub dural()
Location = Sheets("uitleg").Range("A2").Value
Totallocation = Location & "\"
Debug.Print (Totallocation)
checkNum = Sheets("FunBelgium").Range("A1").Value
Debug.Print (checkNum)
lRow = Range("A65536").End(xlUp).Row 'finds last row, assumes contiguous data
j = 1 'first row for your output
For i = 1 To lRow
If Range("A" & i).Value = checkNum Then
Sheets("Output").Range("A" & j & ":N" & j).Value = Sheets("FunBelgium").Range("A" & i & ":N" & i).Value
Rows([i]).EntireRow.Delete
j = j + 1 'advances output row counter if checkNum is found
End If
Next
o = o + 1
Application.ScreenUpdating = True
Sheets("Export").Activate
ActiveSheet.Copy
Thisfile = ActiveSheet.Range("J2").Value
With ActiveSheet.UsedRange
.Copy
.PasteSpecial xlValues
.PasteSpecial xlFormats
End With
Application.CutCopyMode = False
ActiveWorkbook.SaveAs Filename:=Totallocation & Thisfile, FileFormat:=xlCSV, CreateBackup:=True
'ActiveSheet.SaveAs Filename:="C:\Users\sgouman\Downloads\Bernd\" & Thisfile & ".csv"
Application.ScreenUpdating = True
ActiveWorkbook.Close
Sheets("FunBelgium").Activate
If Cells(1, 1) = "" Then
Sheets("Output").Cells.ClearContents
Exit Sub
Else:
Debug.Print ("niet leeg")
Sheets("Output").Cells.ClearContents
j = 0
Call dural
End If
End Sub
So the debug for totallocation is this:
C:\Users\sgouman\Downloads\Bernd\
But I get an 1004 error. If I just manually copy in that file location in the activeworkbook.saveas it works fine.
I believe this is the issue:
Totallocation = Location & "\"
Please replace by this:
Totallocation = Location & "\\"
Reason: the "\" character is a special character, giving another meaning to the next one (e.g. "\n" is newline, "\t" is tab character, ...).
I tried on my PC and there everything is working fine, please debug your VBA code to the "Save" line, and in the immediate window, launch following commands and let us know the results:
?totalLocation
?ThisFile
?totalLocation & Thisfile
This should show you what the filenames look like.
By the way, are you sure your directory is not read-only? Are you even sure that this is the line, causing the issue?

Excel, VBA, .ClearContents with referenced range, error 1004

I'm trying to use .clearcontents on range that is referenced by with some .offset, and I'm having trouble
I know that this works
Sub clear1_1()
Workbooks("xyz").Sheets("abc").range("A2:A3").ClearContents
End Sub
but if I try this it does not
Sub clear2()
Dim region As range
Set region = range("S509:AD618")
Workbooks("xyz").Worksheets("abc").range(region).ClearContents
end sub
I do understand from other postings, that it has something to do with object defyining, but I have no idea where I do mistake, what I need to write.
Final macro is run from one workbook, and is supposed to .clearcontents in other not activated workbook.
My code looks like this
sub Macro()
..... ton of code
Dim filename as string
dim sheetname as string
dim address3, address4 as string
filename = "xyz"
sheetname = "abc" ' both variables that are loaded in other part
address3 and address4 loaded in other part
'here is where i get the error
sheets(sheetname).Range(Range(address3).Offset(0, 12).Address & ":" & Range(address4).Offset(-1, 23)).ClearContents
end sub
I can probably bypass it with .value=""
But I'm looking to learn. Thank you for any response in advance.
EDIT 1
Hi Scott, doesn't make it. Posting bigger part of my code
If mapanchorsuccess = True And map1success = True And map2success = True Then
If Workbooks(Filename).Sheets(startws).Range(address1).Offset(10, 13).HasFormula = True Then
With Workbooks(wbm).Sheets("Report") 'report
.Range("A" & reportrow).Value = runnumber
.Range("B" & reportrow).Value = Filename
.Range("C" & reportrow).Value = Workbooks(Filename).Sheets(startws).Name
.Hyperlinks.Add anchor:=.Range("D" & reportrow), Address:=FilePath & Filename, SubAddress:=Workbooks(Filename).Sheets(startws).Name & "!A1"
.Range("E" & reportrow).Value = "Error"
.Range("F" & reportrow).Value = "rolling probably done already in this sheet"
reportrow = reportrow + 1
End With
Else
With Workbooks(Filename).Sheets(startws)
.Range(Range(address1).Offset(0, 12).Address & ":" & Range(address2).Offset(0, 14).Address).Copy _
Range(Range(address1).Address & ":" & Range(address2).Offset(0, 2).Address)
Application.CutCopyMode = False
.Range(Range(address1).Offset(0, 16).Address & ":" & Range(address2).Offset(0, 16).Address).Copy _
Range(Range(address1).Offset(0, 3).Address & ":" & Range(address2).Offset(0, 23).Address)
Application.CutCopyMode = False
With Workbooks(wbm).Sheets("Report") 'report
.Range("A" & reportrow).Value = runnumber
.Range("B" & reportrow).Value = Filename
.Range("C" & reportrow).Value = Workbooks(Filename).Sheets(startws).Name
.Hyperlinks.Add anchor:=.Range("D" & reportrow), Address:=FilePath & Filename, SubAddress:=Workbooks(Filename).Sheets(startws).Name & "!A1"
.Range("E" & reportrow).Value = "Completed"
.Range("F" & reportrow).Value = "region1 rolled forward"
reportrow = reportrow + 1
End With
.Range(Range(address3).Offset(0, 12).Address & ":" & Range(address4).Offset(-1, 23).Address).Copy _
Range(Range(address3).Address & ":" & Range(address4).Offset(-1, 11).Address)
'///// here the error 1004 occurs
.Range(Range(address3).Offset(0, 12).Address & ":" & Range(address4).Offset(-1, 23).address).clearcontent
End With
End If
End If
The workbook and sheet need to be set with the variable.
Then when using it since it is a range itself just refer to it.
Sub clear2()
Dim region As range
Set region = Workbooks("xyz").Worksheets("abc")range("S509:AD618")
region.ClearContents
end sub
As to your next code; that is a different problem. The ranges inside the () need to allocated to the correct sheet parentage or it will use the active sheet.
The easiest is with a With block:
With sheets(sheetname)
.Range(.Range(address3).Offset(0, 12), .Range(address4).Offset(-1, 23)).ClearContents
End With
I had this same issue, but it turned out to be very simple. I had a row of cells merged together between columns E and F, so when I used this command I had to set the ClearContents from the top corner of my E column to the bottom row of my F column.
What did not work:
Range("E1:E10").Clear Contents
What did work:
Range("E1:F10").ClearContents
I can't believe such a simple thing left me so thwarted.

Trouble Defining a 6th Range Object

I defining different ranges so that I can use them for graphs:
Sub rangesGRAPHS()
Dim count, counter, Erow, Prow1, Prow2, Urow1 As Long
Dim Dsrc1, Dsrc2, Dsrc3, Xsrc1, Xsrc2, Xsrc3 As Range
counter = 5
count = Application.CountA(Range("A:A"))
count = count + 3
While counter < count
If Range("Q" & CStr(counter)) = "ECO_BS" Then Erow = counter
If Range("Q" & CStr(counter)) = "PHO_BS" Then Prow2 = counter
counter = counter + 1
Wend
Prow1 = Erow + 1
Urow1 = Prow2 + 1
Dsrc1 = ("P5:P" & CStr(Erow))
Dsrc2 = ("P" & CStr(Prow1) & ":P" & CStr(Prow2))
Dsrc3 = ("P" & CStr(Urow1) & ":P" & CStr(count))
Xsrc1 = ("$C$5:$C$" & CStr(Erow))
Xsrc2 = ("$C$" & CStr(Prow1) & ":$C$" & CStr(Prow2))
Xsrc3 = ("$C$" & CStr(Urow1) & ":$C$" & CStr(count))
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range(Dsrc1)
ActiveChart.SeriesCollection(1).XValues = ("=SICALIS_Detail!" & Xsrc1)
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range(Dsrc2)
ActiveChart.SeriesCollection(1).XValues = ("=SICALIS_Detail!" & Xsrc2)
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range(Dsrc3)
ActiveChart.SeriesCollection(1).XValues = ("=SICALIS_Detail!" & Xsrc3)
Everything works except the line Xsrc3 = ("$C$" & CStr(Urow1) & ":$C$" & CStr(count)), which gives a error 91: object variable not set.
Upon debugging, I notice that Xsrc3 is set to nothing. However, all the other stuff works and it's written THE SAME WAY. If I comment it out the other stuff still works. I don't understand what is going on - let me know what's up!
It's not actually written the same way. In this line:
Dim Dsrc1, Dsrc2, Dsrc3, Xsrc1, Xsrc2, Xsrc3 As Range
the first 5 variables are actually declared as Variant and only the last is declared as a Range. You actually want them all to be String anyway, so use:
Dim Dsrc1 As String, Dsrc2 As String, Dsrc3 As String, Xsrc1 As String, Xsrc2 As String, Xsrc3 As String

Error '1004' when adding individual cells to a chart range in a loop

I'm trying to add individual cells to a chart so that only cells that meet a certain criteria are added to the chart.
ChartXDataString = "="
ChartFuelDriveDataString = "="
For i = 0 To 5
If Range("AP" & FirstDataRow + i) <> "0" Then
If i = 5 Then
ChartXDataString = ChartXDataString & "'RAW FleetData'!$A$" & (FirstDataRow + i)
ChartFuelDriveDataString = ChartFuelDriveDataString & "'RAW FleetData'!$AP$" & (FirstDataRow + i)
Else
ChartXDataString = ChartXDataString & "'RAW FleetData'!$A$" & (FirstDataRow + i) & ";"
ChartFuelDriveDataString = ChartFuelDriveDataString & "'RAW FleetData'!$AP$" & (FirstDataRow + i) & ";"
End If
End If
Next i
ActiveSheet.ChartObjects("gFMP_TotalFuelLiters").Activate
ActiveChart.SeriesCollection(1).XValues = ChartXDataString
ActiveChart.SeriesCollection(1).Values = ChartFuelDriveDataString
When I run the code Excel throws the following error: Run-time error '1004': Application-defined or object-defined error.
It does so on the line: ActiveChart.SeriesCollection(1).XValues = ChartXDataString
Even when I record a macro adding individual cells, the chart works until I run the recorded macro, where it throws the error.
Help would be much appreciated!
Turns out the macro recorder recorded in the wrong format.
Instead of, as the recorder made,
ChartXDataString = "='RAW FleetData'!$A$2;'RAW FleetData'!$A$3;'RAW FleetData'!$A$4",
the correct format is
"=('RAW FleetData'!$A$2,'RAW FleetData'!$A$3,'RAW FleetData'!$A$4)"
with parentheses and comma separator

Resources