getRange - copyTo not seeing a range that seems like a real range - google-sheets-api

I've got getRange/copyTo working elsewhere in the same script, but it's not working here.
The exception is "Range not found" in this line:
spreadsheet.getRange(copy_from_range).copyTo(copy_to_range, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
While I'm able to use these ranges in other commands:
spreadsheet.setActiveRange(copy_from_range); - this works fine
They don't seem to be recognized as ranges with the getRange/copyTo
I create the range with
var copy_to_range = sheet.getRange(top_row,copy_to_col,num_rows,8);
And it's curious: this only works if I refer to the sheet rather than the spreadsheet, which I get with
var sheet = spreadsheet.getSheets()[0];
But, as I said, both copy_from_range and copy_to_range act normally: I can set the ActiveRange, using toast it comes back "Range".
Any ideas what's going on here?

Figured it out:
getRange wants an a1 notation as input
copyTo wants a range object as input

Related

defining code on vba excel to simplify code writing process

I am attempting to reduce the amount of clutter on my code by creating "shortcuts" if you will
For instance, I always have to type
ThisWorkBook.ActiveSheet.Range
Is there a way for me to define the above to create a less wordy macro? I have tried convert to range and string and the former returns an error (but I could still get intellisense recognize and attempt to autofill) while the string version doesnt work.
Just like in any programming language, you can use variables to store data
For example:
Dim myrange As Range: Set myrange = Sheets("Sheet1").Range("B5")
Alternatively, if you will be working with the same object multiple times, you can use the With keyword
For example. instead of writing you want to work with table every time on every new line you can do
With Sheets("Sheet1").ListObjects("Table1")
.ListRows.Add
.ListColumns(2).Range(3) = "Hello World!"
' ... and so on
End With
Also, please on a sidenote: Avoid using Select/ActiveSheet/ActiveWorkbook and so on!
More info on how to here
You can create functions or customized properties, which are always evaluated when called
Property Get pARng As Range
Set pARng = ThisWorkBook.ActiveSheet.Range
End Property
Function fARng As Range
Set fARng = ThisWorkBook.ActiveSheet.Range
End Function
'Usage
Sub xxx
'...
pARng.Rows(1).Activate
'Same as ThisWorkBook.ActiveSheet.Range.Rows(1).Activate
fARng.Rows(1).Activate
'using function instead achieves same result
End Sub

Dynamically select Excel cells with VB .Net in a VS 2010 project

I'm using Visual Studio 2010, to create a project from a Excel Workbook template. VS2010 already gives me a workbook with one worksheet. I added another one. The project consist of the following files:
ThisWorkbook.vb
Sheet1.vb
Sheet2.vb
Each file consist of class for each object: Sheet1.vb has its Sheet1 class, Sheet2.vb Sheet2 class and so on.
From MSDN help and another sources, I understood I can access from on vb file, or another class, the other class objects using Globals statement:
Me.Range("A10").Value = "Validation time:"
Me.Range("B10").Value = ValidationTime_T1.Item(ValidationTime_T1.Count - 1) - ValidationTime_T0.Item(ValidationTime_T0.Count - 1)
Dim x As Double
Dim rowOffset As Integer
rowOffset = 3
For x = 0 To JobCounter
Globals.Sheet2.Cells(x + rowOffset, 1) = x
Globals.Sheet2.Cells(x + rowOffset, 2) = ASy_Start_Mem.Item(x)
Globals.Sheet2.Cells(x + rowOffset, 3) = WSZ_Start_Mem.Item(x)
Globals.Sheet2.Cells(x + rowOffset, 4) = WSZ_Start_Pk_Mem.Item(x)
Globals.Sheet2.Cells(x + rowOffset, 5) = PFU_Start_Mem.Item(x)
As you can see, I move data from one sheet to another, or put data that is in memory to sheet2 from sheet1.
So far, so good. There were not that many issues I could not solve by my self.
I think is good to point out here that my background is C, C++, Perl and VBA in the last 4 years, so I'm struggling with VB since quite a bit already, I find .Net more useful, until I had to use it with Excel, it is giving me a hard time.
Now, I need to select specific cells base on positions and it is not always the same position so I need to select them dynamically, NO HARD CODED, as I have found in MSDN, forums, StackOverFlow and different sites, the solution they give is to use:
Globals.Sheet2.Range("C7").Select()
And yeah, that's fine for specific cells for which you use a string to select.
The problem is that I need to select different cells every time depending on the each day data, andt I don't know how to do it with Range. In the previous code you can see I used Cells for that.
I've tried:
Globals.Sheet2.Range(Globals.Sheet2.Cells(2, 2), Globals.Sheet2.Cells(6, 3)).Select()
Because one of Range definitions states that I can receive as parameter two Cells objects, but gives an error. I've tried creating Range objects for the cell positions. I have used Object object with CType, and it also fails.
If anyone could help how I can dynamically select cells, either with Range or Cells, or both, or if you have another solution, I will gladly appreciate it.
First thanks to TnTinMn, for replying, and I apologize for the late response again, it's been crazy at work.
Well, I found the solution thanks to your comment.
There seems to be a known issue with Excel.Interop and Visual Basic .Net called "two dots".
Normally, when you go programming VB in VS write a few letter and IntelliSense prompts you with what may be available (property, method or object) then you enter a dot and another list comes up showing you what’s available, once you chose the previous two categories you either assign them to a variable or object, or given them a value. But you can still put another dot and get another list, here is where VB get messed up and not working, probably VS will let you put whenever amount of dos, but at runtime you'll get the error I got.
Hope an experienced StackOverflow fellow can explain this much better.
So the solution for the Select method:
First you need to make the sheet active, then you can use the Select method, as TnTinMn predicted the error was with the Select method.
Globals.Sheet2.Activate()
Globals.Sheet2.Range(Globals.Sheet2.Cells(2, 2), Globals.Sheet2.Cells(6, 3)).Select()
And now Select method does not throw the runtime error.
With the previous code you can now have an option to go through any cell without hard coding.
The following can also be used to store data ranges from different section, to later use in chart for example:
Dim dataX As Excel.Range
Dim dataY As Excel.Range
Dim dataRange As Excel.Range
dataX = Globals.Sheet6.Cells(xRow, XColumn)
dataY = Globals.Sheet6.Cells(yRow, yColumn)
dataRange = Application.Union(dataX, dataY)
Thank you and hope this help someone.

cant get this formula to work, although the top and bottom code works fine

I did a search on this site, but can't find an answer to my problem. I am using VB 2010 Express. I'm trying to write formulas into a Excel spreadsheet.
oWorkSheet = oBook.Sheets(STRName)
'my variables are all declared strings
'this section works
FMLAValue1 = "=-L8"
FMLAValue2 = "=SUM($I$7;$F$8:$H$8)"
FMLAValue3 = "=SUM(M8:U8)"
oWorkSheet.Range("H8").Select()
oWorkSheet.Range("H8").Formula = FMLAValue1
oWorkSheet.Range("H8").AutoFill (oWorkSheet.Range("H8:H40"))
'up to here
'now this is the problem code below: if I paste the formula into a
'excel sheet cell, it works.
oWorkSheet.Range("I8").Select()
oWorkSheet.Range("I8").Formula = FMLAValue2
'**the line above gives an "Exception from HRESULT: 0x800A03EC "**
oWorkSheet.Range("I8").AutoFill (oWorkSheet.Range("I8:I40"))
'this part also works
oWorkSheet.Range("L8").Select()
oWorkSheet.Range("L8").Formula = FMLAValue3
oWorkSheet.Range("L8").AutoFill (oWorkSheet.Range("L8:L40"))
oWorkSheet.Range("J7").Select()
oWorkSheet.Range("J7").Formula = "=I7"
The formula stored in your FMLAValue2 variable doesn't look correct, you shouldn't have a ; (semi-colon) to separate the numbers, you should use a , (comma).
Use this instead:
FMLAValue2 = "=SUM($I$7,$F$8:$H$8)"
and you should hopefully be ok, unless there are other issues somewhere that I haven't noticed.
To test whether a formula is correct, use FormulaDesk. It will immediately tell you if there is an error, and pinpoint exactly where it is in your formula. You can then paste the formula into your VBA code, knowing that it works.
The image below shows how it can pinpoint exactly where your error is within the formula. So in your case, paste the non-working error into a cell in Excel, then view the error report in FormulaDesk to find out the exact cause.
[Disclosure: I am the author of FormulaDesk. I think it will definitely help the poster find any errors]

what mistake Am I doing?

sheet1.activate
activesheet.range(cells(2,"Q"),cells(40,"K")).select 'here the error occurs
selection.copy
The above code works for somtimes and for sometimes throws an Error that with object variable not set what does that mean ? why the above code is not working and if i reopen the file it works again and sometimes dont. But i dont know the reason why it happens. Am i making any mistake in the syntax, If so please let me know the right way to do it. And is there any more efficient way to do to select a set of range ? other than the above ? Thank you in advance
The cause of this error is usually the omission of a Set keyword, e.g.
Dim w as Worksheet
w = Sheet1 ' throws error 91
' Correct syntax:
' Set w = Sheet1
If you tell us on what line the error occurs, then a more specific answer will be forthcoming. The syntax of your code sample looks fine, but the error may be due to another line in your code, perhaps not shown in your question.
Is there any more "efficient" way to do to select a range? Personally, I don't like the method you show, with strings as the arguments for Cells. Strings are messy, and often lead to mistakes and therefore a loss of work efficiency. Why not:
Sheet1.Range(Cells(2,18),Cells(40,11)).Select
' or
Sheet1.Cells(2,11).Resize(39,8).Select
' or
Sheet1.Range("K2").Resize(39,8).Select
Or, define K2:Q40 as a named range in your sheet, calling it e.g. "myRange", and do this:
Sheet1.Range("myRange").Select ' My personal favourite
But why are you using Select? This is usually not necessary. Just write:
Sheet1.Range("myRange").Copy
But then I could ask, why are you using Copy, which is a messy method in its own right?...

How do I use Google.GData.Client.AtomLinkCollection.FindService method to get the list of worksheets in a Google Spreadsheet?

I'm trying to write code that talks to Google Spreadsheets. We do a bunch of processing on our end and then pass data out to our client into this spreadsheet and I want to automate it. This seems like it should be easy.
On this page, Google says "Given a SpreadsheetEntry you've already retrieved, you can print a list of all worksheets in this spreadsheet as follows:"
AtomLink link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);
WorksheetQuery query = new WorksheetQuery(link.HRef.ToString());
WorksheetFeed feed = service.Query(query);
foreach (WorksheetEntry worksheet in feed.Entries)
{
Console.WriteLine(worksheet.Title.Text);
}
Following along at home, I start with:
Dim link As AtomLink = Entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, "")
Dim wsq As New WorksheetQuery(link.HRef.ToString)
and when execution gets to that second line, I find that "Object reference not set to instance of an object." The FindService method is returning nothing. And when I look at GDataSpreadsheetsNameTable.WorksheetRel, it's a constant value of "http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
I'm not really at the point where I even grok what it wants to be doing. E.g., what's a feed? Is a worksheet really what I think it is based on Excel nomenclature? That kind of stuff. But I see a couple of things that might be causing my issue:
The C# method call "...FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);" I'm not sure about that null. It demands a string, so I used "" in my VB, but I'm not sure that's right.
That schemas.google.com URI doesn't seem to be live. At least, if I punch it into a browser, I get server not found. But again, I don't exactly know what it's trying to do.
So, any thoughts? Anyone have VB code that reads Google Spreadsheets and time to instruct a newbie? I'm surprised to find that there's essentially no useful sample code floating around the net.
Thanks for reading!
So, of course, right after I posted this I found some inspiration over here. Manually iterating across the collections works just fine, even if it's not the preferred way to do this. I'm still keen to hear info from others related to this, so feel encouraged to help out even though I'm maybe over this one hurdle.
For Each Entry In mySprShFeed.Entries
If Entry.Title.Text = "spreadsheetNameSought" Then
For Each link As AtomLink In Entry.Links
If link.Rel = GDataSpreadsheetsNameTable.WorksheetRel Then
Dim wsf As WorksheetFeed = service.Query(New WorksheetQuery(link.HRef.ToString))
For Each worksheet In wsf.Entries
Console.WriteLine(worksheet.Title.Text)
Next
End If
Next
End If
Next