Using MS project vba on an excel workbook, i want to move a worksheet to the leftmost tab - ms-project

This is what I have so far
Sub SetupExcel(ByRef xlApp As Excel.Application, ByRef xlbook As Excel.Workbook)
Set xlApp = New Excel.Application
Set xlbook = xlApp.Workbooks.Add
Dim xlsheet As Excel.worksheet
End Sub
sub Main_routine
Call SetupExcel(xlApp, xlbook)
call CreateTaskGraphics()
..... create a bunch of additional tabs in this workbook
goto Exit_Here:
Exit_Here
xlApp.Worksheets("Task Graphics").Select
xlbook.Sheets("Task Graphics").Move Before:=Sheets(Worksheets.Count)`** "<---- this is failing
..... closing statements
End Sub
So, this consists of many subs and a main routine. The CreateTaskGraphics routine create a tab and places text and buttons on it. The only thing failing is the next to last statement
in the "Exit_Here" section where I want to move the "Task Graphics" tab to be leftmost in the workbook. I have used every combination I can think of to preceed the Sheets("Task Graphics")... statement, such as xlBook, xlWorkbook, xlsheet, xlapp, etc. I cannot find any combination that works.Does anyone have any ideas?

To move a worksheet to the beginning (e.g. left-most) position:
xlbook.Sheets("Task Graphics").Move Before:=xlbook.Sheets(1)
To add it as the left-most sheet in the first place:
Set xlsheet = xlbook.Worksheets.Add(Before:=xlbook.Worksheets(1))
When using the Sheets or Worksheets collection, remember to specify the workbook object; otherwise the active workbook is presumed which might not be what was intended.

Related

How to copy workbook (.aspx file) from html link to current workbook

I have trouble with the following tasks in excel VBA:
At my work, we use a document management platform called TeamShare: [https://www.lector.dk/en/products/]
I want to create a code in VBA, that loops over a range of links to this document management platform in my workbook, ie. loops over other workbooks, opens them and then copies a specified sheet to my current workbook.
I have tried putting together bits of codes from other sites, and the code works just fine when i run it in break mode. However, when I run the code all at once, the Excel program reopens, such that the current workbook cannot "communicate" with the opened workbook and I end up in an infinity loop (so no direct error message).
This is the code that only works in break mode:
Dim wbCopyTo As Workbook Dim wsCopyTo As Worksheet Dim i As Long Dim Count As Long Dim WBCount As Long Dim LastRow As Long Dim wb As Workbook Dim ws As Worksheet Dim URL As String Dim IE As Object Dim doc As Object Dim objElement As Object Dim objCollection As Object
Set wbCopyTo = ActiveWorkbook Set wsCopyTo = ActiveSheet
LastRow = wsCopyTo.Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
The purpose of this piece of code is to get the DocID
A = InStr(wsCopyTo.Range("B" & i), "documentid=") + Len("documentid=")
B = InStrRev(wsCopyTo.Range("B" & i), "&")
DocID = Mid(wsCopyTo.Range("B" & i), A, B - A)
'Get URL
URL = wsCopyTo.Range("B" & i)
'Count number of open workbooks
WBCount = Workbooks.Count
With IE
New is the comman that opens excel sheet. This works as planned in breakmode, however the excel program reopens when i run the code all at once. I have tried other commandos here: "Workbooks.Open", I couldn't get this one to open the file and "Application.FollowHyperlink" only worked in break mode too, however, much much slower
.Navigate URL
'This was my solution to how to stop the rest of the code from executing until the new workbook has loaded.
Do Until Workbooks.Count = WBCount + 1: Loop
End With
'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
'So in order to activate the workbook from the URL, I am looping over all my open workbooks and matching them on their unique Document ID. I found that the workbook from the URL wasn´t the "active workbook" per default.
For Each book In Workbooks If Mid(book.Name, 12, Len(DocID)) = DocID Then
book.Activate
Set wb = ActiveWorkbook
Set ws = ActiveSheet
End If
Next book
Here i copy the desired sheet to my initial workbook
wb.Worksheets("SpecificSheetIWantToCopy").Copy After:=wbCopyTo.Worksheets("Sheet1") wbCopyTo.Sheets(ActiveSheet.Name).Name = DocID
Next i
End Sub
I am using excel 2010.
I hope you can help me resolve this problem. Please ask if you need any more information, that i haven´t provided.
Thanks in advance.

Excel column values being appended as rows instead of columns into datatable

I have an Excel file which I need to read through and extract particular values of a certain range into a datatable so I can then save that data into a table in a database.
Whilst debugging, on every loop I check the datatable visualizer to see what's going on and I find that I'm appending values of a different row, to the same row. Example in photo.
SamplePhoto
Here is the code responsible for that action.(Surrounded in a Try-Catch)
Using excel As New ExcelPackage (ulTarget.PostedFile.InputStream)
Dim _worksheet = excel.Workbook.Worksheets.First()
Dim _hasHeader = True
For Each cell In _worksheet.Cells(1,2,147,4)
_dataTable.Columns.Add(If(_hasHeader, cell.Value, String.Format("{0}", cell.Start.Column)))
If _worksheet.Cells.Value Is Nothing Then
Continue For
Next
Assume that the range 1,2,147,4 is correct as the data going into the datatable is correct, the row seperation is simply the problem. _dataTable is my DataTable (obvious I know but nothing bad in clarifying it) and _hasHeader is set to True because the Excel worksheet being uploaded has headers and I don't want them being put into the DataTable because the data will all end up in a table in SQL Server where appropriate column names exist.
Also ulTarget is my File uploader. I am using EPPlus most recent version for this.
Anybody have any suggestions as to how I can seperate the data into rows as per the example in the photo above? Happy to make any clarifications if needed.
Added the horizontal range of the columns without headers and read each cell row by row.
Using excel As New ExcelPackage(ulTargetFile.PostedFile.InputStream)
'Add the columns'
Dim _worksheet = excel.Workbook.Worksheets.First()
Dim _hasHeader As Boolean = False
For Each col In _worksheet.Cells("B1:D1")
_dataTable.Columns.Add(If(_hasHeader, Nothing, col.Value))
String.Format("{0}", col.Start.Column)
Next
'Add the rows'
For rowNumber As Integer = 1 To 147
Dim worksheetRow = _worksheet.Cells(rowNumber, 2, rowNumber, 4)
Dim row As DataRow = _dataTable.Rows.Add()
For Each cell In worksheetRow
row(cell.Start.Column - 2) = cell.Value
Next
Next

Exporting data from PowerPivot

I have an enormous PowerPivot table (839,726 rows), and it is simply too big to copy-paste into a regular spread sheet. I have tried copying it and then reading it directly into R using the line data = read.table("clipboard", header = T), but neither of these approaches work. I am wondering if there is some add-on or method I can use to export my PowerPivot table as a CSV or .xlsx? Thanks very much
Select all the PowerPivot table
Copy the data
Past the data in a text file (for example PPtoR.txt)
Read the text file in R using tab delimiter: read.table("PPtoR.txt", sep="\t"...)
To get a PowerPivot table into Excel:
Create a pivot table based on your PowerPivot data.
Make sure that the pivot table you created has something in values area, but nothing in filters-, columns- or rows areas.
Go to Data > Connections.
Select your Data model and click Properties.
In Usage tab, OLAP Drill Through set the Maximum number of records to retrieve as high as you need (maximum is 9999999 records).
Double-click the measures area in pivot table to drill-through.
another solution is
import the Powerpivot model to PowerBi desktop
export the results from PowerBI desktop using a Powershell script
here is an example
https://github.com/djouallah/PowerBI_Desktop_Export_CSV
A pure Excel / VBA solution is below. This is adapted from the code here to use FileSystemObject and write 1k rows at a time to the file. You'll need to add Microsoft ActiveX Data Objects Library and Microsoft Scripting Runtime as references.
Option Explicit
Public FSO As New FileSystemObject
Public Sub ExportToCsv()
Dim wbTarget As Workbook
Dim ws As Worksheet
Dim rs As Object
Dim sQuery As String
'Suppress alerts and screen updates
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
'Bind to active workbook
Set wbTarget = ActiveWorkbook
Err.Clear
On Error GoTo ErrHandler
'Make sure the model is loaded
wbTarget.Model.Initialize
'Send query to the model
sQuery = "EVALUATE <Query>"
Set rs = CreateObject("ADODB.Recordset")
rs.Open sQuery, wbTarget.Model.DataModelConnection.ModelConnection.ADOConnection
Dim CSVData As String
Call WriteRecordsetToCSV(rs, "<ExportPath>", True)
rs.Close
Set rs = Nothing
ExitPoint:
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
Set rs = Nothing
Exit Sub
ErrHandler:
MsgBox "An error occured - " & Err.Description, vbOKOnly
Resume ExitPoint
End Sub
Public Sub WriteRecordsetToCSV(rsData As ADODB.Recordset, _
FileName As String, _
Optional ShowColumnNames As Boolean = True, _
Optional NULLStr As String = "")
'Function returns a string to be saved as .CSV file
'Option: save column titles
Dim TxtStr As TextStream
Dim K As Long, CSVData As String
'Open file
Set TxtStr = FSO.CreateTextFile(FileName, True, True)
If ShowColumnNames Then
For K = 0 To rsData.Fields.Count - 1
CSVData = CSVData & ",""" & rsData.Fields(K).Name & """"
Next K
CSVData = Mid(CSVData, 2) & vbNewLine
TxtStr.Write CSVData
End If
Do While rsData.EOF = False
CSVData = """" & rsData.GetString(adClipString, 1000, """,""", """" & vbNewLine & """", NULLStr)
CSVData = Left(CSVData, Len(CSVData) - Iif(rsData.EOF, 3, 2))
TxtStr.Write CSVData
Loop
TxtStr.Close
End Sub
Here is a lovely low-tech way:
https://www.sqlbi.com/articles/linkback-tables-in-powerpivot-for-excel-2013/
I think the process is a little different in Excel 2016. If you have Excel 2016, you just go to the data tab, go to Get External Data, and then Existing Connections (and look under Tables).
The other important thing is to click on Unlink (under Table Tools - Design - External Table Data). This unlinks it from the source data, so it really is just an export.
You can copy that data into another workbook should you wish to.
Data in Power Pivot is modeled, using DAX Studio to export data to csv or SQL.
after finished, you will see that Each model corresponds to a CSV file or SQL table.

ASP.NET to Excel export - reference file and open save as dialog?

I have this code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Here we go. All the data in the form to an Excel sheet. Cross your fingers...
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel- this isn't really what I need though, I need it to open a template and populate it.
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open("C:\Users\jagtars\Desktop\HI Resources\HI.xlsx")
'Add data to cells of the first worksheet in the new workbook
oSheet = oBook.Worksheets(1)
oSheet.Range("H5").Value = CustomerName.Text
oSheet.Range("K5").Value = dropdown_serverVirtualisation.Value
oSheet.Range("L5").Value = dropdown_desktopVirtualisation.Value
oSheet.Range("M5").Value = dropdown_oracle.Value
oSheet.Range("N5").Value = dropdown_sqlServer.Value
'etc....
'Save the Workbook and Quit Excel
oBook.SaveAs("C:\Users\jagtars\Desktop\HI.xlsx")
MessageBox.Text = "Exported!"
MessageBox.Focus()
oExcel.Quit()
End Sub
This code grabs a file from a folder in my desktop and then edits it and saves it as a new file 'HI' in my Desktop.
Instead I would like to place this file in my project folder and then reference it and after that the user should get the option to where they want to save the new modified file.
What do I need to modify in my code to achieve this?
Thanks All.
You should use HttpResponse.WriteFile method. Browser will automatically show dialog to user. To get path inside you project you could use HttpServerUtility.MapPath

How can I copy object types in VB.NET?

I am building an ASP.NET application that needs dynamic tables. That's another issue that I've already posted about (and gotten a pretty good response!). Now, I'm running into another issue - I want to add new rows to my table, but given that I will have 10-12 tables on one page, each containing different objects in their rows (text boxes, check boxes, etc.) I need a way of simply generically adding a new row that has the same objects as the first row in the table. Here's my code:
Private Sub AddTableRow(ByRef originalTable As System.Web.UI.WebControls.Table)
Dim originalRow As System.Web.UI.WebControls.TableRow = originalTable.Rows(1)
Dim insertingRow As New System.Web.UI.WebControls.TableRow
Dim insertingCells(originalRow.Cells.Count) As System.Web.UI.WebControls.TableCell
Dim index As Integer = 0
For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells
insertingCells(index) = New System.Web.UI.WebControls.TableCell
insertingCells(index).Controls.Add(cell.Controls.Item(0))
index += 1
Next
insertingRow.Cells.AddRange(insertingCells)
originalTable.Rows.Add(insertingRow)
End Sub
But I'm getting a null reference exception at the second to last line,
insertingRow.Cells.AddRange(insertingCells)
...and I can't figure out why. Is it because the contents of each cell are not being initialized with a new object? If so, how would I get around this?
Thanks!
EDIT:
The inside of my for loop now looks like this -
For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells
Dim addedContent As New Object
Dim underlyingType As Type = cell.Controls.Item(0).GetType
addedContent = Convert.ChangeType(cell.Controls.Item(0), underlyingType)
insertingCells(index) = New System.Web.UI.WebControls.TableCell
insertingCells(index).Controls.Add(addedContent)
index += 1
Next
Stepping through with a debugger, I see that this strategy is working - but the additional table row still doesn't appear...and still does when I do this statically.
I think your culprit may be this line:
Dim insertingCells(originalRow.Cells.Count) As TableCell
Confusingly, the number you specify in an array declaration in VB.NET is the upper bound, not the number of elements. So Dim ints(10) As Integer will create an Integer() array with eleven elements, not ten (10 will be the highest index of the array).
Try this instead:
Dim insertingCells(originalRow.Cells.Count - 1) As TableCell

Resources