Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27513

VS 2008 Running an Excel macro from VB2008

$
0
0
I have written a program that needs to import data from an Excel spreadsheet. To do so I have created a Macro in Excel called "LoadAndFormatRates" that removes several unwanted lines and then some spaces between words so that they are single words. I have written the following code to run the macro from VB2008:

Imports System.Data.Odbc
Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim cn As OdbcConnection = New OdbcConnection
cn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls)};Dbq=C:\FXEXRATESTest.xls;Uid=Admin;Pwd=;"
cn.Open()

'Define Xcel objects
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook

'Start Excel and open the workbook

xlWorkBook = xlApp.Workbooks.Open("C:\FXEXRATESTest.xls")

'Run the macro
xlApp.Run("LoadAndFormatRates")
'Clean-up: Close the Workbook and quit Excel
xlWorkBook.Close(False)
'Quit the Excel Application
xlApp.Quit()
'Clean up
releaseObject(xlApp)
releaseObject(xlWorkBook)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

but as soon as it reaches the RUN(LoadAndFormatRates) it throws up the following message:

Cannot run the macro 'LoadAndFormatRates'. The macro may not be available in this workbook or all macros may be disabled.

I have searched various Forums to find an answer for this error but without success.

Can anyone throw some light upon the matter?

Kind regards

Viewing all articles
Browse latest Browse all 27513

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>