Excel worksheets in vb.net - vb.net

Is there a way when to make the current worksheet your on in excel to be the worksheet shown when changing worksheets in vb.net? Say I'm on worksheet 1 and change it to worksheet 2 through vb.net, If I enter in data it will show up on worksheet two but in order to see the data I have to physically go to the excel file and select worksheet 2 in order to change the actually worksheet page being displayed.

Tried this code and it seems to work on my side. The trick is the method sheet.Activate()
Sub Main
Dim excelApp as Microsoft.Office.Interop.Excel.Application = _
new Microsoft.Office.Interop.Excel.Application()
Try
Dim inFile As String = "D:\temp\test.xls"
' Show excel '
excelApp.Visible = true
Dim excelWorkbook As Microsoft.Office.Interop.Excel._Workbook = _
excelApp.Workbooks.Open(infile)
Dim x as Integer
for x = excelApp.Sheets.Count to 1 step -1
Dim sheet as _Worksheet = CType(excelApp.Sheets(x), _Worksheet)
sheet.Activate() ' Activate the sheet'
Thread.Sleep(5000) ' Sleep for 5 seconds to see the sheet'
Next
Finally
if excelApp IsNot Nothing then
excelApp.DisplayAlerts = false
'excelApp.Quit(); 'remove the comment to close excel'
End if
End try
End Sub

Related

Export Power Queries from One Workbook to Another with VBA

I am looking to transfer power queries from one workbook to another with VBA. I know how to do this manually but it is very cumbersome.
A power query can be accessed via the Workbook.Connections object.
I am currently attempting to port the queries over with a VBA function or Sub.
The manual process is as follows
for each query in workbook 1
open up workbook 1 and go to advanced editor - copy into a text editor
open up workbook 2 create query, and paste text into advanced editor
ensure source tables are the same - and run query to validate
I was able to solve it by using the Workbook.Query object.
here is my solution.
Public Sub FunctionToTest_ForStackOverflow()
' Doug.Long
Dim wb As Workbook
' create empty workbook
Set NewBook = Workbooks.Add
Set wb = NewBook
' copy queries
CopyPowerQueries ThisWorkbook, wb, True
End Sub
Public Sub CopyPowerQueries(wb1 As Workbook, wb2 As Workbook, Optional ByVal copySourceData As Boolean)
' Doug.Long
' copy power queries into new workbook
Dim qry As WorkbookQuery
For Each qry In wb1.Queries
' copy source data
If copySourceData Then
CopySourceDataFromPowerQuery wb1, wb2, qry
End If
' add query to workbook
wb2.Queries.Add qry.Name, qry.formula, qry.Description
Next
End Sub
Public Sub CopySourceDataFromPowerQuery(wb1 As Workbook, wb2 As Workbook, qry As WorkbookQuery)
' Doug.Long
' copy source data by pulling data out from workbook into other
Dim qryStr As String
Dim sourceStrCount As Integer
Dim i As Integer
Dim tbl As ListObject
Dim sht As Worksheet
sourceStrCount = (Len(qry.formula) - Len(Replace$(qry.formula, "Source = Excel.CurrentWorkbook()", ""))) / Len("Source = Excel.CurrentWorkbook()")
For i = 1 To sourceStrCount
qryStr = Split(Split(qry.formula, "Source = Excel.CurrentWorkbook(){[Name=""")(1), """]}")(0)
For Each sht In wb1.Worksheets
For Each tbl In sht.ListObjects
If tbl.Name = qryStr Then
If Not sheetExists(sht.Name) Then
sht.Copy After:=wb2.Sheets(wb2.Sheets.Count)
End If
End If
Next tbl
Next sht
Next i
qryStr = qry.formula
End Sub
Function sheetExists(sheetToFind As String) As Boolean
'http://stackoverflow.com/questions/6040164/excel-vba-if-worksheetwsname-exists
sheetExists = False
For Each sheet In Worksheets
If sheetToFind = sheet.Name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function

vba excel: how to copy worksheet with images but without buttons

i have a worksheet with an image and 2 buttons. (invoice)
i would like to copy the worksheet with the image but without the 2 buttons into a new sheet of a new workbook and i wanna do it with a vba macro.
in the moment i do it with the usual copy command and use an extra delete command for the 2 buttons.
i am sure there is a easier way to do it.
i tried this...
Application.CopyObjectsWithCells = False
Sheets("invoice").Select
Sheets("invoice").Move After:=Workbooks("invoices").Sheets(1)
Application.CopyObjectsWithCells = True
these looses the buttons but the image is also gone. but i would like to keep the image.
i hope you guys can help me with this.
thanks in advance.
The explanations are in the comments in the code below:
Option Explicit
Sub CopySheet_WO_Btn()
Dim newWB As Workbook
Dim ShtOrig As Worksheet
Dim Obj As OLEObject
Dim PicShape As Shape
Dim PicLeft As Double
Dim PicTop As Double
Set ShtOrig = ThisWorkbook.Sheets("invoice")
' loop through all objects in "invoice" sheet
For Each Obj In ShtOrig.OLEObjects
' if OLE Object is type CommanButton make it Un-Visible (not to copy with the sheet)
If Obj.progID = "Forms.CommandButton.1" Then
Obj.Visible = False
End If
Next Obj
Set newWB = Workbooks.Add(xlWBATWorksheet)
ShtOrig.Copy newWB.Sheets(1)
' loop through all shapes in "invoice" sheet and copy the pictures
For Each PicShape In ShtOrig.Shapes
If PicShape.Name = "Picture 1" Then
PicLeft = PicShape.Left
PicTop = PicShape.Top
PicShape.Copy
newWB.Sheets(1).Paste
Selection.ShapeRange.Left = PicLeft
Selection.ShapeRange.Top = PicTop
End If
Next PicShape
' loop again and return the CommandButtons to be Visible in "invoice" sheet
For Each Obj In ShtOrig.OLEObjects
Obj.Visible = True
Next Obj
End Sub

Deleting empty worksheets

I'm trying to write a code to delete empty worksheets in a workbook. So far I have been able to delete worksheets starting at the highest to the lowest using the code:
Dim i As Integer
Dim objExcel As Object = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Dim objWorkbook As Excel.Workbook = objExcel.Workbooks.Open(TextBox1.Text)
i = objWorkbook.Worksheets.Count
Do Until i = 2
objWorkbook.Worksheets(1).Delete()
i = i - 1
Loop
I had a look on the internet, but didn't find something that can be useful. Can anyone help me by guiding me to the right direction where I can obtain information on how to detect for empty worksheets in a single workbook using VB.net only.
Thank You
This should do the trick in vb.net
Private Sub DeleteBlankWorksheets(xlWorkBook As Excel.Workbook)
For i As Integer = xlWorkBook.Worksheets.Count To 1 Step -1
Dim ws As Excel.Worksheet = CType(xlWorkBook.Worksheets(i), Excel.Worksheet)
If Convert.ToInt64(ws.UsedRange.CountLarge) <= 1 Then
ws.Delete()
End If
Next
End Sub
Replace your entire loop with a call to this function, passing your objWorkBook object as the parameter.
Dim objExcel As Object = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Dim objWorkbook As Excel.Workbook = objExcel.Workbooks.Open(TextBox1.Text)
DeleteBlankWorksheets(objWorkbook)
'Add this to save the file
objWorkbook.Save()
objWorkbook.Close() 'closes the files
'If you have trouble with the file object being still opened, meaning you can see the EXCEL.exe in the task manager then add the following code
For Each instance As Process In Process.GetProcesses
If InStr(instance.MainWindowTitle, Textbox1.Text) <> 0 Then p.Kill()
Next
NOTE: It is better to make sure to dispose of all of your excel objects (applications, workbooks, worksheets, etc) than to kill processes. This will ensure all data is preserved as intended without side effects. If you find you have extra excel.exe instances running, make sure to double check everything is disposed and released properly.
This will do the job
Sub DeleteBlankWs()
Dim ws As Worksheet
For Each ws In Worksheets
If WorksheetFunction.CountA(ws.Cells) = 0 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
End Sub
I created an excel with 5 sheets, sheet 2 and 4 are empty, then I edited a micro and run it (F5 key or the green play icon)...

How to define an object inside a for loop for excel vba

I want to import data from multiple workbooks, all from the same sheet index (3).
I'm new to vba, and I figured out how to open multiple files up, and also to copy data from one sheet to another sheet in a different workbook for a single file, but I can't seem to figure out how to do that for multiple files.
I highlighted where the error is, it tells me "object doesn't support this property or method"
Could you please help?
Thanks
Sub dataimport()
' Set Vars
Dim ArbinBook As Workbook, DataBook As Workbook
Dim i As Integer, j As Integer
Dim Caption As String
Dim ArbinFile As Variant, DataFile As Variant
' make weak assumption that active workbook is the target
Set DataBook = Application.ActiveWorkbook
' get Arbin workbook
Caption = "Please select an input file"
' To set open destination:
' ChDrive ("E")
' ChDir ("E:\Chapters\chap14")
' With Application
'Set "arbinfile" as variant, the "true" at end makes it into an array
ArbinFile = Application.GetOpenFilename(, , Caption, , True)
'Exit when canceled
If Not IsArray(ArbinFile) Then
MsgBox "No file was selected."
Exit Sub
End If
Dim targetSheet As Worksheet
Set targetSheet = DataBook.Sheets(1)
'Open for every integer i selected in the array "arbinfile"
For i = LBound(ArbinFile) To UBound(ArbinFile)
Set ArbinBook = Workbooks.Open(ArbinFile(i))
targetSheet.Range("A2", "G150").Value = ArbinBook.Sheets(3).Range("A2", "G150").Value
**ERROR at the line above**
Workbooks(DataSheet).Activate 'Reactivate the data book
Worksheets(1).Activate 'Reactivate the data sheet
ActiveWorkbook.Sheets(1).Copy _
after:=ActiveWorkbook.Sheets(1)
Workbooks(ArbinFile(1)).Activate 'Reactivate the arbin book(i)
ArbinBook.Close
Next i
Beep
End Sub
My instinct tells me that ArbinBook.Sheets(3) is a Chart-sheet, not a WorkSheet (or, at least, it is something other than a WorkSheet). It might be hidden as well, but it will still be indexed as (3).
If so, change Sheets(3) to Worksheets(3).
Added: BTW If true, this also demonstrates why using index-numbers is unreliable. If at all possible, refer to a worksheet by its name. (I appreciate that this may not always be possible.)
Added (from comments) There is nothing named DataSheet in your code. Add Option Explicit to the top of your module to indicate all such errors.
Try changing the line Set ArbinBook = Workbooks.Open(ArbinFile(i))
to Set ArbinBook = Workbooks(arbinfile(i))
I could be wrong, but I think it's trying to set your workbook object to become the action of opening another workbook, instead of labeling it as the workboook.
Sub Multiple()
Application.DisplayAlerts = False
Application.EnableEvents = False
Dim exlApp As Excel.Application
Dim exlWb1 As Excel.Workbook
Dim exlWb2 As Excel.Workbook
Dim exlWb3 As Excel.Workbook
Dim exlWs1 As Excel.Worksheet
Dim exlWs2 As Excel.Worksheet
Dim exlWs3 As Excel.Worksheet
Set exlApp = CreateObject("Excel.Application")
Set exlWb1 = exlApp.Workbooks.Open("C:\yourpath1\file1.xls")
Set exlWb2 = exlApp.Workbooks.Open("C:\yourpath2\file2.xls")
Set exlWb3 = exlApp.Workbooks.Open("C:\yourpath3\file3.xls")
Set exlWs1 = exlWb.Sheets("Sheet1")
Set exlWs2 = exlWb.Sheets("Sheet1")
Set exlWs3 = exlWb.Sheets("Sheet1")
exlWb1.Activate
exlWb2.Activate
exlWb3.Activate
'code
exlWb.Close savechanges:=True
exlWb.Close savechanges:=True
exlWb.Close savechanges:=True
Set exlWs1 = Nothing
Set exlWs2 = Nothing
Set exlWs3 = Nothing
Set exlWb1 = Nothing
Set exlWb2 = Nothing
Set exlWb3 = Nothing
exlApp.Quit
Set exlApp = Nothing
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub

Opening a workbook with VBA/macro is making it read only?

I would like my code to open a workbook (always the same one), detect the first free row, write to just two cells in that row, and then save/close the workbook. This seems like a simple problem, but the macro seems to be opening a copy of the file, and then locking it for editing.
Can you see any errors in my open code? I know that the file opens and that the row search works, but then it 1. never writes to the cells, and 2. locks the file.
Function WriteToMaster(Num, Path) As Boolean
'Declare variables
Dim xlApp As Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim infoLoc As Long
Set xlApp = New Excel.Application
'Specifies where the Master Move Key is stored
Set wb = xlApp.Workbooks.Open("DOC LOCATION")
Set ws = wb.Worksheets("Sheet1")
'Loop through cells, looking for an empty one, and set that to the loan number
infoLoc = firstBlankRow(ws)
MsgBox "First blank row is " & infoLoc & ". Num is " & Num
ws.Cells(infoLoc, 1).Value = Num
ws.Cells(infoLoc, 2).Value = Path
'Save, close, and quit
wb.Save
wb.Close
xlApp.Quit
'Resets the variables
Set ws = Nothing
Set wb = Nothing
Set xlApp = Nothing
'pieces of function from http://p2p.wrox.com/vb-how/30-read-write-excel-file-using-vb6.html
End Function
Thank you again, stackoverflow <3
Do you need to open a new excel app just to open a workbook?
Can't you just do something like this:
Sub Macro1()
Dim wkb As Workbook
Workbooks.Open Filename:="\User Documents$\bob\My Documents\workbook_open_example.xlsx"
Set wkb = Workbooks("workbook_open_example.xlsx")
End Sub