Add combobox to selected file Visual Studio 2010 VB - visual-studio-2010

i want to make an .exe file using VS2010 to select excel file, and read it's sheets through a combobox.
I have now sorted to make a 'browse' button to select the excel file and generate a msgbox but yet couldn't assign the combobox to read it's sheets.
here is my code
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Public Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Dim myFileDlog As New OpenFileDialog()
'Dim oXL As Excel.Application
'Dim oWB As Excel.Workbook
'Dim oSheet As Excel.Worksheet
'look for files in the c drive
myFileDlog.InitialDirectory = "c:\"
'specifies what type of data files to look for
myFileDlog.Filter = "All Files (*.*)|*.*" & _
"|Data Files (*.xls)|*.xls" & _
"|Data Files (*.xlsx*)|*.xlsx*" & _
"|Data Files (*.xlsm*)|*.xlsm*"
'specifies which data type is focused on start up
myFileDlog.FilterIndex = 2
'Gets or sets a value indicating whether the dialog box restores the current directory before closing.
myFileDlog.RestoreDirectory = True
'seperates message outputs for files found or not found
If myFileDlog.ShowDialog() = _
DialogResult.OK Then
If Dir(myFileDlog.FileName) <> "" Then
MsgBox("File Exists: " & _
myFileDlog.FileName, _
MsgBoxStyle.Information)
Else
MsgBox("File Not Found", _
MsgBoxStyle.Critical)
End If
End If
'Adds the file directory to the text box
txtFileDirectory.Text = myFileDlog.FileName
End Sub
Public Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
'Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
'Dim oRng As Excel.Range
For x As Integer = 1 To FileDialog.Sheets.Count()
If TypeOf oWB.Sheets(x) Is Excel.Worksheet Then
ComboBox1.Items.Add(FileDialog.Sheets(x).name)
End If
Next
ComboBox1.SelectedIndex = 0
End Sub
End Class
Thanks in advance!

You need to set your workbook oWB first and then use the below.
Change
If TypeOf oWB.Sheets(x) Is Excel.Worksheet Then
ComboBox1.Items.Add(FileDialog.Sheets(x).name)
End If
to
If TypeOf oWB.Sheets(x) Is Excel.Worksheet Then
ComboBox1.Items.Add(oWB.Sheets(x).name)
End If
Similarly FileDialog.Sheets.Count() is incorrect

Related

Download Excel direct to drive (C:\) (No save as option require) VBA Excel

I am new in VBA. Please help me to download the excel file direct in to my drive. I have only option to click the element and it prompt of "Save As" dialog box.
Application.StatusBar = "Saving - Dashboard.xlsx"
Set InputElement = doc.querySelector("span.export[class='export excel'")
If Not InputElement Is Nothing Then
InputElement.Click
I am running this code every hour, I can't click save as button every hour.
I was thinking to download auto downloader, but did not get much success. Coz, I have have admin right and out of policy.
Public Sub OpenIE_Login()
Set IE = New InternetExplorer
IE.Visible = True
IE.Navigate cURL
Do While IE.readyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop ''' ATTENTION - PAUSE HERE
Set doc = IE.Document
Set LoginForm = doc.forms(0)
Set InputElement = doc.querySelector("input#userName[id='userName']")
If Not InputElement Is Nothing Then
InputElement.Value = cUsername
End If
'
Set InputElement = doc.querySelector("input.field[type='password']")
If Not InputElement Is Nothing Then
InputElement.Value = cPassword
End If
Application.StatusBar = "Saving - WokingHours.xlsx"
Set InputElement = doc.querySelector("span.export[class='export excel'")
'Dim TempStr As String
If Not InputElement Is Nothing Then
'TempStr = InputElement.Value
InputElement.Click
End Sub
You did not posted the code which actually downloads the file. In title of the thread, You said VBA Excel but your code using IE object.
If you have the URL of the file than you can refer example below for downloading the file.
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Sub demo()
Dim strURL As String
Dim LocalFilePath As String
Dim DownloadStatus As Long
strURL = "http://data.iana.org/TLD/tlds-alpha-by-domain.txt"
LocalFilePath = "C:\Users\panchals\Desktop\sample.txt"
DownloadStatus = URLDownloadToFile(0, strURL, LocalFilePath, 0, 0)
If DownloadStatus = 0 Then
MsgBox "File Downloaded. Check in this path: " & LocalFilePath
Else
MsgBox "Download File Process Failed"
End If
End Sub
You need to modify the code as per your own requirement.
Reference:
Download Files with VBA URLDownloadToFile

edit through visual studio an msword file

i am trying a program that can edit an existing ms word document through an instant editing at a visual studio 2010 program but im having trouble. my codes:
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim wd1 As Word.Application
Dim wd1Doc As Word.Document
wd1 = New Word.Application
wd1.Visible = True
wd1Doc = wd1.Documents.Add("C:\Users\DELL\Desktop\activity6\profile.dotx")
With wd1Doc
.FormFields("w_name").Range = TextBox1.Text
.FormFields("w_age").Range = TextBox2.Text
End With
wd1 = Nothing
wd1Doc = Nothing
End Sub
End Class
the errors says: "property range is read only"
Your code is almost correct. If you want to the the text of a Range object, you need to use its .Text property:
With wd1Doc
.FormFields("w_name").Range.Text = TextBox1.Text
.FormFields("w_age").Range.Text = TextBox2.Text
End With

Error when creating MS Excel docs with VB 2010

I'm having some trouble with looping and creating MS Excel docs, code snippet below
Private Sub selectedRowsButton_Click( _
ByVal sender As Object, ByVal e As System.EventArgs) _
Handles selectedRowsButton.Click
Dim selectedRowCount As Integer = _
DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
If selectedRowCount > 0 Then
Dim sb As New System.Text.StringBuilder()
Dim objexcel As New Excel.Application
Dim i As Integer
Dim FACode As Integer
Dim Sitename As Integer
Dim Sitecode As Integer
Dim Address As Integer
Dim City As Integer
Dim State As Integer
Dim ZIP As Integer
FACode = 1
Sitename = 5
Sitecode = 2
Address = 6
City = 7
State = 9
ZIP = 10
Dim xlWorkbook As Excel.Workbook
xlWorkbook = objexcel.Workbooks.Open("template path")
For i = 0 To selectedRowCount - 1
objexcel.Visible = True
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
objexcel.Range("B3").Value = DataGridView1.SelectedCells(Sitecode).Value.ToString()
objexcel.Range("B5").Value = DataGridView1.SelectedCells(FACode).Value.ToString()
Dim thisfile As Object
thisfile = objexcel.Range("B5").Value & "." & _
objexcel.Range("B3").Value & "." & "otherstring" & "." & "otherstring2" & "." & ".xls"
With objexcel
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile)
'~~> Close the Excel file without saving
xlWorkbook.Close(False)
End With
Next i
End If
I'm getting the error Exception from HRESULT: 0x800A03EC for the statement
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
IF I select only one row of my DataGrid before creating the program works fine, it is when I select multiple rows that this error occurs. Since I'm creating the program specifically for multiple row selections I'm stumped as to where I've gone wrong. Any help or pointers appreciated, Thanks!
Two things
You have declared objexcel As Excel.Application so you shouldn't use objexcel.Range("B2").Value. Use xlWorkbook.Range("B2").Value. Change it everywhere in your code.
You cannot use SaveAs like that. See the snapshot below. If you want to save as xls file then you have to use FileFormat:=56
See this code example
'~~> Save As file
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile, FileFormat:=56)
If you do not specify the file format then you will get an error message when you open the file after opening.
You might want to look at this link on how to automate Excel from VB.Net
Topic: VB.NET and Excel
Link: http://www.siddharthrout.com/vb-dot-net-and-excel/
I am not too sure what you exactly are trying to do with the DGV. Like Sean mentioned you are not incrementing the values. If you can post a snapshot of how your DGV looks and how your Excel file should look after the export then we can help you in a much better way :)

Visual Studio. How to copy record from database to word .doc and print it

In Visual studio 2010>New Project>Visual Basic>Windows>Windows forms Application, i have made a form (form1.vb) and a database (Local Database>"Database1.sdf") and a Table with 3 Columns ("Name","City","Age").
I like to copy this 3 fields and paste to document "test1.doc" (open this with Ms Office or Open Office Writer). I have bookmarks ("PasteName", PasteCity", "PasteAge") in specified places in test1.doc .
How to make a button to open the document "test1.doc" and copy - paste this 3 items from table to doc and preview before print it? (not for save - only print preview and close without save after printing)
I have find this code for MS Office but didn't work in Visual Studio. I like something similar. (this code is for a doc Form Fields - I have Bookmarks in my doc).
Private Sub cmdPrint_Click()
Dim appWord As Word.Application
Dim doc As Word.Document
Set appWord = GetObject(, "Word.Application")
Set appWord = New Word.Application
Set doc = appWord.Documents.Open("C:\WordForms\CustomerSlip.doc", , True)
With doc
.FormFields("fldCustomerID").Result = Me!CustomerID
.FormFields("fldCompanyName").Result = Me!CompanyName
.FormFields("fldContactName").Result = Me!ContactName
.Visible = True
.Activate
End With
Set doc = Nothing
Set appWord = Nothing
End Sub
Thanks programers people
This works for me. (button action)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Print customer slip for current customer.
Dim appWord As Word.Application
Dim doc As Word.Document
'Avoid error 429, when Word isn't open.
On Error Resume Next
Err.Clear()
'Set appWord object variable to running instance of Word.
appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
'If Word isn't open, create a new instance of Word.
appWord = New Word.Application
End If
doc = appWord.Documents.Open("D:\Test.docx", , True)
doc.Visible()
doc.Activate()
With doc.Bookmarks
.Item("Name").Range.Text = Me.NameID.Text
.Item("City").Range.Text = Me.CityID.Text
End With
Dim dlg As Word.Dialog
dlg = appWord.Dialogs.Item(Word.WdWordDialog.wdDialogFilePrint)
dlg.Display()
'doc.Printout
doc = Nothing
appWord = Nothing
Exit Sub
errHandler:
MsgBox(Err.Number & ": " & Err.Description)
End Sub

How to programmatically set contact image in Outlook 2007?

How could we automatically/programmatically set the sender/contact image in outlook 2007? They are colleagues, and all employees pictures are stored in netshare.
I see that Outlook.ContactItem has an AddPicture method. Here's an example straight out of the help file:
Sub AddPictureToAContact()
Dim myNms As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myContactItem As Outlook.ContactItem
Dim strName As String
Dim strPath As String
Dim strPrompt As String
Set myNms = Application.GetNamespace("MAPI")
Set myFolder = myNms.GetDefaultFolder(olFolderContacts)
strName = InputBox("Type the name of the contact: ")
Set myContactItem = myFolder.Items(strName)
If myContactItem.HasPicture = True Then
strPrompt = MsgBox("The contact already has a picture associated with it. Do you want to overwrite the existing picture?", vbYesNo)
If strPrompt = vbNo Then
Exit Sub
End If
End If
strPath = InputBox("Type the file name for the contact: ")
myContactItem.AddPicture (strPath)
myContactItem.Save
myContactItem.Display
End Sub

Resources