Export with VB to Excel and update file - vb.net

This is the code that i have to export data to Excel.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
oSheet.Range("A1").Value = "ID"
oSheet.Range("B1").Value = " Nome"
oSheet.Range("A1:B1").Font.Bold = True
oSheet.Range("A2").Value = CStr(Request("ID"))
oSheet.Range("B2").Value = "John"
oBook.SaveAs("C:\Book1.xlsx")
oExcel.Quit()
I can create and save the excel file, but i can't update the contents.
How can i do it?
Thanks.

You're trying to set a Range to a value, I think either you need to set a Range to an array that can contain the value(s) or you need to set a single Cell to a single value.
This link shows how to do either:
http://support.microsoft.com/kb/301982

I think you want:
oBook = oExcel.Workbooks.Open ("C:\Book1.xlsx")
When you choose Add, you are creating a new workbook.
If you are confident there are no gaps, something like this may suit:
''Last cell in column A, or first gap
oSheet.Range("a1").End(xlDown).Select
''A+1 row
oSheet.ActiveCell.Offset(1) = "a"
''A + 1 row + 1 col
oSheet.ActiveCell.Offset(1, 1) = "b"
''A + 1 row + 2 col
oSheet.ActiveCell.Offset(1, 2) = "c"
Otherwise, you may need http://support.microsoft.com/kb/142526 to determine the last cell.

Related

vb.net do while excel cell value is not "test value"

I'm a new VB.net user (and completely self taught).
I'm trying to search down column A of an excel workbook (starting at "A1") to check the cell contents. On finding a specific value, I want to msgbox out which cell it is in.
Can anybody help me in how to code this please.
Having played with various things over the day, I've finally got it to work!!!
How I've done it - it seems simple now I've worked it out:
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
' For the first sheet in an excel workbook
xlWorkSheet = CType(objApp.Sheets(1), Microsoft.Office.Interop.Excel.Worksheet)
Dim strSheetName As String = xlWorkSheet.Name
' ***** Find the row with "Ambient Temp (C)" as its header
AmbientRange = objAppDeckCalc.Worksheets(strSheetName).Range("a1")
TempValue = AmbientRange.Value
Do While TempValue <> "Ambient Temp (C)"
AmbientRange = AmbientRange.Offset(1, 0)
TempValue = AmbientRange.Value
CountRow = CountRow + 1
If CountRow = 100 Then
MsgBox("Fields Not Named Correctly!")
End
End If
Loop
MsgBox("Ambient Temp (C) - CountRow - " & CountRow)

Filling pre-exisitng Excel form using vbscript

Running an old Classic ASP site, and up to now I made my own "Excel" file with HTML, that gets sent to our accounting dept. They've revised the Excel file they want us to use, so I can't use my old method. So I'm connecting to the excel file directly (ADODB), and I can update the necessary cells easily enough. The problem is that they've added some fields at the bottom of the "form", including some with SUM() formulas, and left 34 rows for entries in the middle. We often need more than that.
I've tried "insert into" sql, and tried "rs.AddNew", and those both put the data into the row below the range I'm targeting; fair enough. However a NEW ROW is not added to the file - the data goes into the row below. It isn't like inserting a row manually in Excel, and pushing any lower rows further down. Does anyone know how I can do this through ADO/SQL? Or is it simply impossible?
As a last resort, I'll just have to create an extra document to hold the overflow past 34 entries.
Thanks!
I finally found something that reflects my problem, but it is VBA (I think):
Const xlDown = -4121
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open(“C:\Scripts\Test.xls”)
Set objWorksheet = objWorkbook.Worksheets(1)
Set objRange = objExcel.Range(“A1”)
objRange.End(xlDown).Activate
intRow = objExcel.ActiveCell.Row
intColumn = objExcel.ActiveCell.Column
Set objRange = objWorksheet.Cells(intRow, intColumn).EntireRow
For i = 1 to 10
objRange.Insert(xlShiftDown)
Next
For i = 1 to 10
objExcel.Cells(intRow, 1).Value = i
intRow = intRow + 1
Next
strFormula = “=SUM(A1:A” & intRow – 1 & “)”
objExcel.Cells(intRow, 1).Formula = strFormula
Any way to make this work on a server in VBscript??? :-)
Since you can't do this using ADO (you'd just end up overwriting your formulae) you will need to directly access the workbook. The code you found is close but what's below should fit your needs. Let me know if you need any further explanation?
Option Explicit
Const xlDown = -4121
Const xlUp = -4162
Dim objExcel, objWorkbook, objRange, iLastRow, myRecordCount, numInserts, intLoop
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\Test.xls")
Set objWorksheet = objWorkbook.Worksheets(1) ' refers to first worksheet
iLastRow = objWorksheet.Cells(objWorksheet.Rows.Count, 1).End(xlUp).Row
Set objRange = objWorksheet.Cells(iLastRow, 1).EntireRow
' myRecordCount will need to hold the number of records you have
If myRecordCount > 34 Then
numInserts = myRecordCount - 34 ' get the number of rows to be inserted
Else
numInserts = 0
End If
For intLoop = 1 to numInserts
' for as many rows as we need, insert above the formula
objRange.Insert(xlShiftDown)
Next
' insert your data into the worksheet here
objWorkbook.Save
objWorkbook.Close
objExcel.Quit
' send the file out however you're sending it

MS Word VBA: Controlling excel workbook from word - Object required error

I'm creating a MACRO in MS Word that needs to be able to (basically) copy and paste the contents of a table in word into excel.
DISCLAIMER: This might seem like an over complication; however, the approach is required as it is a setup for more complicated processing.
Long story short, I loop through every table in the document, and then every cell in the table and place the text into a corresponding cell in an excel sheet.
I have these declarations for excel objects:
'Objects
Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlRange As Excel.Range
At the bottom of my loops, I have the following code:
xlBook.Worksheets(x).Activate
Set xlRange = xlBook.ActiveSheet.Range(Chr(65 + x) & y)
xlRange.Text = tString
The last line is throwing an "object required" error. The variable tstring is defined as a string and is set earlier in the loop.
The full code:
Sub CopyTablesToExcel()
'Constants
Const COLUMN_INDEX = 1
Const ROW_INDEX = 2
'Ints
Dim x As Integer, y As Integer, z As Integer 'Counters
Dim numTables As Integer 'Number of tables in the word file
Dim numSheets As Integer 'Number of sheets in the excel file
Dim LastCell(1 To 2) As Integer 'Used to keep track of the last cell of a newly created excel table
Dim map() As Integer 'Holds a map of the table columns
'strings
Dim xlBookName As String 'Name of the excel workbook
Dim tString As String 'Temporary string
'Objects
Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlRange As Excel.Range
'Initialize
Set xlBook = xlApp.Workbooks.Add
numSheets = xlBook.Worksheets.count
numTables = ActiveDocument.Tables.count
'Save the new book
xlBookName = InputBox("Enter the ticker symbol:")
xlBook.SaveAs FileName:=xlBookName
'Show the file?
xlApp.Visible = True
'Make sure there are enough sheets
If numSheets < numTables Then
For x = 1 To (numTables - numSheets)
xlBook.Worksheets.Add
numSheets = numSheets + 1
Next
End If
'Cycle through every table in the document and paste it to the worksheet
For z = 1 To numTables 'Cycle through tables
'Keep track of the last cell in the table
LastCell(COLUMN_INDEX) = ActiveDocument.Tables(z).Columns.count
LastCell(ROW_INDEX) = ActiveDocument.Tables(z).rows.count
For x = ActiveDocument.Tables(z).rows(ActiveDocument.Tables(z).rows.count).Cells.count To 1 Step -1 'Cycle through columns
'Used selections to support horizontally merged cells
ActiveDocument.Tables(z).rows(ActiveDocument.Tables(z).rows.count).Cells(x).Select
Selection.SelectColumn
For y = Selection.Cells.count To 1 Step -1 'Cycle through cells
tString = Selection.Cells(y).Range.Text
'Move the content into excel
xlBook.Worksheets(x).Activate
Set xlRange = xlBook.ActiveSheet.Range(Chr(65 + x) & y)
Debug.Print Chr(65 + x) & y 'Prints as expected
xlRange.Text = tString
Next
Next
Next
End Sub
I believe this is happening because the MACRO is failing to set the xlRange correctly. The output from debug.print is correct and is the format of "A#".
EDIT:
If Not xlRange Is Nothing Then
xlRange.Text = tString 'Still errors
End If
The above will evaluate to true but still throws the error at the marked line
I see two things:
.Text is a read only property. I would expect an an "Unable to set the text property of range object" error on this line:
xlRange.Text = tString
Change to:
xlRange.Value = tString
Also, your range assignment is probably wrong. I don't know why you are doing CHR(65) instead of simply "A", but the problem is this line:
Set xlRange = xlBook.ActiveSheet.Range(Chr(65 + x) & y)
Here you are ADDING x to 65, and then the Chr function returns whatever result that is, which could raise an error. A value of x that is greater than 25 will most likely raise an error becasue then Chr(65 + x) does not evaluate to a valid range address.
Since you clarify in the comments that you do intend to do this (e.g., "A" + 1 = "B", etc.), it would be better probably to do this, if for no other reason than it seems more legible and leverages the Excel object model in a less-ambiguous manner:
Set xlRange = xlBook.ActiveSheet.Range("A" & y).Offset(,x)

Using column names in spreadsheet no index, using vb,net

I have been writing some code to extract data from a an application and parse it to a spreadsheet.
My spreadsheet looks like this:
Scenario ClientName ClientNumber
5555 Smith s0001
6776 Charles d6666
I have this code:
Dim ObjExcel As New Excel.Application
Dim sWindow As New WinWindow
ObjExcel.Visible = False
Dim stext As String
ObjExcel.Workbooks.Open("c:\data\calcresults.xlsx")
Dim ObjWS As Excel.Worksheet = ObjExcel.Worksheets("IP")
Dim iNextRow As Integer = ObjWS.UsedRange.End(Excel.XlDirection.xlDown).Row + 1
ObjWS.Cells(iNextRow,1 ) = "d66666"
ObjWS.Cells(iNextRow, 2) = "s77898"
would like use to Column Name not index, for example:
ObjWS.Cells(iNextRow,"Scenario" ) = "new row data, first column"
any ideas how can i do this?
I am guessing by your post that you are opening a workbook and updating the same column values each time?
What you could do is name the Range in Excel by selecting the cell in the sheet and entering the name into the Name Box as follows:
Then you can manipulate as follows:
Dim r1 As Range
Set r1 = ActiveSheet.Range("Scenario")
r1.Value = "OOps, changed it!"
r1.Offset(1, 0).Value = "This is A2"
Additionally you can just refer to the range:
Dim r As Range
Set r = ActiveSheet.Range("A1")
r.Value = "gello"
You can also set the name of a range for more than one cell - i.e. multiple rows/columns. Then manipulate with:
Dim r2 As Range
Set r2 = ActiveSheet.Range("SomethingElse")
r2.Cells(1) = "Summit Else 0"
r2.Cells(2) = "Summit Else 1"
r2.Cells(3) = "Summit Else 2"
I cannot see anything wrong with just accessing row/col index.

Excel VBA - UsingVBA to create a new, formatted workbook

I'm trying to write the last part of my program and I need to pull data from an Access document and print it into a new Workbook.
To start, I will be taking the names of product Suppliers and creating a Worksheet with each suppliers name, then I want to be looping through each sheet and printing the products from each supplier that were ordered.
I'm really struggling with wrapping my head around how to open a new workbook and print in my info.
As my previous answer was deleted (considered "insuficient"), I have to provide a better one.
If you want to output data from Access to Excel, you have to follow this steps:
Create (or open) a new workbook
Read your data
Write your data to the workbook
Format the data in the workbook
I will focus on the data output, and leave the formatting out (the data part is the complicated one... formatting is easy)
First, you need to enable the Excel objects in your Access file: Tools Menu > References. Find the Microsoft Excel 12.0 Object Library and activate the checkbox. Now you have the full Excel library at your service :-)
Now is the time for the data crunching. I will asume that you need to create a new workbook:
public sub createExcelFile()
dim XL as Excel.Application, WB as Excel.Workbook, WKS as Excel.Worksheet
dim db as DAO.database, rec as DAO.recordset, f as DAO.field
dim i as integer, j as integer
' Prepare your Excel stuff
Set XL = new Excel.Application
XL.Visible = True
Set WB = XL.Workbooks.Add
WB.Activate
Set WKS = WB.ActiveSheet ' Default: The first sheet in the newly created book
' Read your data here
set db = currentdb()
set rec = db.openrecordset("tblSampleData")
' A simple table that will show the data from rec
' i and j will be the coordiantes of the active cell in your worksheet
with rec
.movefirst
' The table headers
i = 1
j = 1
for each f in .fields
WKS.cells(i,j).value = f.name
j = j + 1
next f
' The table data
do
i = i+1
j = 1
for each f in .Fields
WKS.cells(i,j).value = f.value
j = j+1
next f
.moveNext
loop until .EOF
end with
end sub
If you want to format the cells, you can use the WKS.cells(i,j) (or WKS.range(...)) properties.
Take a look at the link I leaved before (which Siddarth Rout was kind to move to the comments).
I hope this helps you
Option Compare Database
Public Function format(filepath, sheetname)
Set xls = CreateObject("EXCEL.APPLICATION")
xls.screenupdating = False
xls.displayalerts = False
xls.Visible = True
xls.workbooks.Open filepath
Set xlsdd = xls.ActiveWorkbook
'deleting headers
xls.Range("1:1").Select
xls.Selection.Delete Shift:=xlUp
'adding one column
xls.Columns("A:A").Select
xls.Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'adding 5 rows
'ActiveWorkbook.Sheets("sheet1").Select
xls.Rows("1:5").Insert Shift:=xlDown
'fetching rows from access and putting them into excel
strsql = "select top 5 " & sheetname & ".* into top5_records from " & sheetname
DoCmd.RunSQL strsql
outputFileName = "C:\Users\hp\Desktop\top5_records.xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "top5_records", outputFileName, True
'then open that excel and copy the rows
Set xls2 = CreateObject("EXCEL.APPLICATION")
xls2.screenupdating = False
xls2.displayalerts = False
xls2.Visible = True
xls2.workbooks.Open outputFileName
Set xlsdd2 = xls.ActiveWorkbook
xls2.Rows("1:5").Select
xls2.Selection.Copy
xls.Cells(1, 1).Select
xls.activesheet.Paste
' Dim currdb As DAO.Database
' Dim rst As DAO.Recordset
'
' Set currdb = CurrentDb
' Set rst = currdb.OpenRecordset(strsql) '<<<Opens query recordset via DAO
' rst.MoveLast
' rowsToReturn = rst.RecordCount
' Set rng = xls.Cells(1, 1)
' 'copy specified number of records to worksheet
'
'rng.CopyFromRecordset rst, rowsToReturn '<<<Gets all records in recordset
'making first 6th row to be bold
xls.Rows("6:6").Select
With xls.Selection.Font
.Bold = True
.Name = "Arial"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
End With
'autofit the data
xls.Sheets(sheetname).Cells.Columns.autofit
xls.CutCopyMode = False
With xlsdd
.Save
.Close
End With
xls.Visible = False
Set xlsdd = Nothing
Set xls = Nothing
End Function
You can define column/row widths to a static pixel amount or auto-fit, things like bold are a pre-defined
Example Selection.Font.Bold = True
You can also make a template spreadsheet, copy the contents into the template and save as.
Your post does not indicate how much formatting actually needs to be done.
You don't give a lot of details, so I can't give you a lot of details in return. But here's how I would do it:
Create a new workbook manually with two sheets
On one sheet, add an External Data table that returns a list of supplier's name like SELECT SupplierName FROM tblSuppliers WHERE Active=True; or something like that.
Create a workbook-level named range that dynamically expands with that query table
On the second sheet, add an External Data table like SELECT * FROM Orders WHERE SupplierName=? (This will be a parameter query). Start that external data table in row 3
I row, put a combobox box that points back to the supplier list.
Now the VBA is simple
ThisWorkbook.RefreshAll
Instead of one sheet per supplier, you'll have one sheet on which you can change the supplier. Here are the skills you'll need
Create an external data table
Create a parameter query (old reference http://www.dicks-clicks.com/excel/ExternalData6.htm)
Create dynamically expanding range name
Add a combobox or data validation that points to a range on a different sheet
That SQL above is obviously not right, but I assume you can write the correct SQL statement
You should be able to find details on all that, but if not, post another question.