VBA - Method or data member not found when opening an excel file from access - excel

I have a small application that connects to a SQL server and downloads some of the data to Excel. It works fine in my computer but in the computer of one of my coworkers I get a "Method or Data member not found" error when trying to change the content of a cell in the excel spreadsheet.
This is the code that fails in my coworker computer, the line that has the error is the last line:
Public Function ExportRequest(strSupplier As String, intSupplier As Integer, _
strOutPath As String, iEmpty As Integer, strManager As String, _
ichkVolume As Integer, iframeVolume As Integer, ichkMatNum As Integer) As String
On Error GoTo err_Handler
' Excel object variables
Dim appExcel As Excel.application
Dim wbk As Excel.Workbook
Dim wks As Excel.Worksheet
Dim wksvol As Excel.Worksheet
Dim wsRange As Excel.Range
Dim wksvolRange As Excel.Range
Dim sTemplate As String
Dim sTempFile As String
Dim sOutput As String
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim sSQL As String
Dim sDateFrom As String
Dim sDateTo As String
Dim lRecords As Long
Dim iRow As Integer
Dim iCol As Integer
Dim iFld As Integer
Dim intYear As Integer
Const cStartRow As Byte = 3
Const cStartColumn As Byte = 1
intYear = year(Now)
DoCmd.Hourglass True
' set to break on all errors
application.SetOption "Error Trapping", 0
' start with a clean file built from the template file
sTemplate = ap_GetConfig("NegTemplatePath") & ap_GetConfig("NegTemplate")
sOutput = strOutPath & "\Price Template " & strSupplier & "-2020" & ".xlsm"
If Dir(sOutput) <> "" Then Kill sOutput
FileCopy sTemplate, sOutput
' Create the Excel Applicaiton, Workbook and Worksheet and Database object
Set appExcel = Excel.application
Set wbk = appExcel.Workbooks.Open(sOutput)
wbk.Sheets("Price List").Visible = xlSheetVisible
Set wks = appExcel.Worksheets("Price List")
wks.UnProtect Password:="irishstout"
wks.Cells(1, 2) = strSupplier
Hopefully someone has run into something similar?

In MS Office object model, all methods, properties, and events follow a hierarchical structure. Usually, the Application object usually initializes top level items. All others would derive from its descendants. Therefore, the Excel.Application would not contain properties for worksheets or ranges. See examples below.
Excel
Methods: Application > Workbooks > Add / Open ...
Properties: Application > Workbook > Worksheets / Queries / Path ...
Events: Application > Workbook > Activate / BeforeClose ...
Set appExcel = New Excel.Application
Set wbk = appExcel.Workbooks.Open("C:\Path\MyWorkbook.xlsx")
Set wks = wbk.Worksheets("My Sheet")
wks.Name = "My New Name"
Word
Methods: Application > Add / Open ...
Properties: Application > Document > Paragraphs / Table / Bookmarks ...
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open("C:\Path\MyDocument.docx")
Set wdPara = wdDoc.Paragraphs(1)
wdDoc.Tables.Add(NumRows=3, NumColumns=3)
Access
Methods:
Application > OpenCurrentDatabase > CurrentDb ...
Application > DoCmd > OpenForm / OpenReport ...
Properties:
Application > CurrentDb > TableDefs / QueryDefs ...
Application > CurrentProject > AllForms / AllReports ...
Events: Application > CurrentProject > AllForms > Form > AfterUpdate / BeforeClose ...
Set appAccess = New Access.Application
Set accFile = appAccess.OpenCurrentDatabase("C:\Path\MyDatabase.accdb")
Set db = accFile.CurrentDb()
appAccess.DoCmd.OpenForm("My Form")

Related

Run-time error '462': The remote server machine does not exist or unavailable - Populating word document from excel with content controls / VBA

Attempting to create a template document that can be pre-populated / generated from an excel template.
Not overly experienced with VBA so I currently have a lot of repeating code. Nonetheless it seems to work okay but only runs successfully maybe 1/3 times.
On failed attempts I get the following error message:
Run-time error '462': The remote server machine does not exist or unavailable
Any help appreciated
Option Explicit
Sub Gen_Proposal()
Dim wrdApp As Word.Application
Dim WdDoc As Word.Document
Dim BmkNm As String
Dim newBooktxt As String
Dim FileNm As String
Dim Customer As String
Dim State As String
Dim ProposalType As String
Dim Version As String
Dim ProjectNum As String
Dim ProposalDate As String
Dim ws As Excel.Worksheet
'Select Proposal input excel sheet
Set ws = Excel.Worksheets("Sheet1")
Customer = ws.Range("Customer").Value
State = ws.Range("State").Value
ProposalType = ws.Range("ProposalType").Value
Version = ws.Range("Version").Value
ProjectNum = ws.Range("ProjectNum").Value
ProposalDate = ws.Range("ProposalDate").Value
Set wrdApp = CreateObject("Word.Application")
FileNm = Application.ActiveWorkbook.Path & "\Template.docx"
Set WdDoc = wrdApp.Documents.Add(FileNm)
wrdApp.Visible = True
Dim oCC As ContentControl
Set oCC = ActiveDocument.SelectContentControlsByTitle("Customer").Item(1)
oCC.Range.Text = Customer
Set oCC = ActiveDocument.SelectContentControlsByTitle("State").Item(1)
oCC.Range.Text = State
Set oCC = ActiveDocument.SelectContentControlsByTitle("ProposalType").Item(1)
oCC.Range.Text = ProposalType
Set oCC = ActiveDocument.SelectContentControlsByTitle("Version").Item(1)
oCC.Range.Text = Version
Set oCC = ActiveDocument.SelectContentControlsByTitle("ProjectNum").Item(1)
oCC.Range.Text = ProjectNum
Set oCC = ActiveDocument.SelectContentControlsByTitle("ProposalDate").Item(1)
oCC.Range.Text = ProposalDate
WdDoc.Fields.Update
WdDoc.PrintPreview
WdDoc.ClosePrintPreview
wrdApp.Activate
End Sub

Accessing One Drive files offline in VB .Net

I am working on an application that stores it's files in the Documents folder to easily sync with One Drive. I need to make them available offline, in case of an outage. I have changed the settings so that I have a local copy. When I click directly on the Excel file in File Explorer, the program opens it with no problem. However, when I try to open the file in my application, I get an error stating "No network found..." etc. Is there another way to do this? Thanks in advance.
Public Sub LoadMemberList()
lstMemberList.Clear()
Dim mMember As Members
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim range As Excel.Range
xlApp = New Excel.Application
xlBook = xlApp.Workbooks.Open(CurrentYearPath) '***This is where the exception is thrown.
xlSheet = xlBook.Worksheets("sheet1")
range = xlSheet.UsedRange
Dim rs As Object(,) = CType(range.Value, Object(,))
Dim records As Long = rs.GetUpperBound(0)
If records > 1 Then
For x = 2 To records
mMember.MemberNumber = FormatNumber(rs(x, 1))
mMember.MemberName = rs(x, 4) + " " + rs(x, 3)
lstMemberList.Add(mMember)
Next
End If
xlBook.Close()
xlApp.Quit()
KillExcel()
xlApp = Nothing
xlBook = Nothing
xlSheet = Nothing
range = Nothing
End Sub
Public Function CurrentYearPath() As String
Dim CurrentYear As Integer
CurrentYear = CInt(Format(Now, "yyyy"))
Return My.Computer.FileSystem.SpecialDirectories.MyDocuments + "\DailyBook\Rosters\Membership" + CurrentYear.ToString + ".xlsx"
End Function
Scroll down here
https://learn.microsoft.com/en-us/onedrive/plan-onedrive-enterprise#key-onedrive-features
and you'll find this,
However, if you plan to access a file while disconnected from the internet, you can make the file available offline by right-clicking it, and then selecting Always keep on this device.

VBA Reaching Active Excel Workbook from Another Applicatiom

I am trying to make program to see the excel workbook that is already open, but it doesn't. Controlling with xlApp.Visible = True line creates a new excel document instead making the open one visible. Any suggestions please?
Edit: I added the rest of the code here. Using catia, I am trying to reach the open excel worksheet and make modifications on it. In this case I am trying to select A1:E5 cells one by one and clear their contents
Sub CATMain()
Dim xlApp As Excel.Application
'On Error Resume Next
Set xlApp = VBA.GetObject("", "Excel.Application")
Dim exlBook As Workbook
Set exlBook = xlApp.ActiveWorkbook
Dim exlSheet As Worksheet
Set exlSheet = xlApp.ActiveSheet
xlApp.Visible = True
Dim cell1 As Integer
Dim cell2 As Integer
Dim cell3 As Integer
Dim cell4 As Integer
Dim myRange As Range
cell1 = 1 'InputBox("Tablo Başlangıç Satırını Girin: ")
cell2 = 1 'InputBox("Tablo Başlangıç Sütununu Girin: ")
cell3 = 5 'InputBox("Tablo Bitiş Satırını Girin: ")
cell4 = 5 'InputBox("Tablo Bitiş Sütununu Girin: ")
Set myRange = exlSheet.Range(Cells(cell1, cell2), Cells(cell3, cell4))
myRange.ClearContents
End Sub

VB.NET: Excel Crashes when Updating Data in a Word Chart

Update: Releasing objects has no effect on Excel crashing. The problematic line is:
Dim wChartData = wChart.ChartData
I have written a VB.Net application that opens a word document, iterates through the inline shapes, and updates each chart with data from the database. Sometimes Excel will crash when opening the sheet containing the chart data. Can anyone tell me how I fix this?
Here is the code that iterates through the shapes:
wApp = New Word.Application
wApp.Visible = True
wDoc = wApp.Documents.Add("Some_File_Name.docx")
Console.WriteLine("Updating Charts")
Dim chartName As String
For Each wShape As Word.InlineShape In wDoc.InlineShapes
If wShape.HasChart = Core.MsoTriState.msoTrue Then
If wShape.Chart.HasTitle Then
chartName = wShape.Chart.ChartTitle.Text
Else
chartName = "NO_TITLE"
End If
UpdateChart(wShape.Chart, reportID, reportTitle,
reportUser, curriculumYear, chartName)
End If
Next
The UpdateChart subroutine grabs a SQL query and some options related to the chart, then fires off the FillChartData subroutine below:
Public Sub FillChartData(ByRef wChart As Word.Chart, ByVal sql As String,
Optional ByVal addDataPointsToLabels As Boolean = False)
If sql = "" Then Exit Sub
Dim cmd = O.factory.CreateCommand()
cmd.CommandText = sql
cmd.Connection = O.con
O.factory.CreateDataAdapter()
Dim adapter = O.factory.CreateDataAdapter
adapter.SelectCommand = cmd
Dim dt As New System.Data.DataTable()
Dim ds As New System.Data.DataSet()
adapter.Fill(ds, "report_name")
dt = ds.Tables(0)
Dim wChartData = wChart.ChartData
Dim wChartWb As Excel.Workbook = wChartData.Workbook
Dim wChartSheet As Excel.Worksheet = wChartWb.Sheets(1)
Dim title As String = "No title"
If wChart.HasTitle Then title = wChart.ChartTitle.Text.ToString
Dim r As Excel.Range
r = wChartSheet.Range("A1")
r.CurrentRegion.Clear()
For i = 0 To dt.Columns.Count - 1
Dim c As System.Data.DataColumn = dt.Columns(i)
r.Offset(0, i).Value2 = c.ColumnName
Next
r = wChartSheet.Range("A2")
For Each row As System.Data.DataRow In dt.Rows
For i = 0 To row.ItemArray.Count - 1
r.Offset(0, i).Value2 = row.Item(i)
Next
r = r.Offset(1)
Next
r = wChartSheet.Range("A1")
If addDataPointsToLabels Then
While r.Value <> ""
r.Value &= " " & r.Offset(1).Value
r = r.Offset(0, 1)
End While
End If
wChartWb.Close()
releaseObject(r)
releaseObject(wChartSheet)
releaseObject(wChartWb)
releaseObject(wChartData)
r = Nothing
wChartSheet = Nothing
wChartWb = Nothing
wChartData = Nothing
GC.Collect()
End Sub
The releaseObject subroutine is as follows:
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
MessageBox.Show(ex.ToString)
obj = Nothing
End Try
End Sub
And here's the crash report:
Problem signature:
Problem Event Name: APPCRASH
Application Name: EXCEL.EXE
Application Version: 15.0.5007.1000
Application Timestamp: 5a5eb36d
Fault Module Name: EXCEL.EXE
Fault Module Version: 15.0.5007.1000
Fault Module Timestamp: 5a5eb36d
Exception Code: c0000005
Exception Offset: 002b71c8
OS Version: 6.1.7601.2.1.0.256.4
Locale ID: 1033
Additional information about the problem:
LCID: 1033
skulcid: 1033
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
Thanks for your help!
You need to Activate the Word ChartData object to begin the inter-process communication between Word and Excel.
The example below is a simplified demonstration of code pattern and contains no error handling. This example also demonstrates releasing out of scope COM objects via the garbage collector. See this answer for more discussion on this COM clean-up procedure.
This code was verified against Office 2007.
Imports System.Runtime.InteropServices
Imports Excel = Microsoft.Office.Interop.Excel
Imports Word = Microsoft.Office.Interop.Word
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
InterOpWork("Embedded Excel Chart.docx")
COMCleanup()
End Sub
Sub InterOpWork(filePath As String)
Dim appWord As New Word.Application
Dim doc As Word.Document = appWord.Documents.Open((filePath))
Dim shp As Word.InlineShape = doc.InlineShapes(1)
Dim ch As Word.Chart = shp.Chart
Dim chData As Word.ChartData = ch.ChartData
chData.Activate() ' **** This is what your code is missing
Dim wb As Excel.Workbook = DirectCast(chData.Workbook, Excel.Workbook)
Dim appExcel As Excel.Application = DirectCast(wb.Application, Excel.Application)
Dim ws As Excel.Worksheet = DirectCast(wb.Worksheets("Sheet1"), Excel.Worksheet)
Dim rng As Excel.Range = ws.Range("B2:B4")
Dim dataToChange As Object(,) = DirectCast(rng.Value2, Object(,))
For i As Int32 = dataToChange.GetLowerBound(0) To dataToChange.GetUpperBound(0)
dataToChange(i, 1) = i * 2 + (5 - i)
Next
rng.Value = dataToChange
wb.Save()
wb.Close(False)
appExcel.Quit()
doc.Save()
doc.Close(False)
appWord.Quit()
End Sub
Private Sub COMCleanup()
Do
GC.Collect()
GC.WaitForPendingFinalizers()
Loop While Marshal.AreComObjectsAvailableForCleanup
End Sub
End Class

VBA OnSlideShowPageChange crashes when adding slide in presentation mode

I've been working with the code below and can't seem to figure out what's causing PowerPoint to crash on the last line. I've used the same block of code in other subs without issue. I suspect this may somehow be related to the onslideshowpagechange function.
The code runs through the VBA editor in PowerPoint with the following libraries.
Reference Libraries
I essentially want the code to execute when a slide change occurs in presentation mode. The part of the code that causes the crash I want to add a slide back in.
Thanks ahead of time for any help!
Public Function GetLayout( _
LayoutName As String, _
Optional ParentPresentation As Presentation = Nothing) As CustomLayout
If ParentPresentation Is Nothing Then
Set ParentPresentation = ActivePresentation
End If
Dim oLayout As CustomLayout
For Each oLayout In ParentPresentation.SlideMaster.CustomLayouts
If oLayout.Name = LayoutName Then
Set GetLayout = oLayout
Exit For
End If
Next
End Function
Sub onslideshowpagechange(ByVal SSW As SlideShowWindow)
Dim oXL As Object 'Excel.Application
Dim oWb As Object 'Excel.Workbook
Dim oSld As Slide
' Check excel workbook file status, if not open then open
Dim file_status
file_status = IsWorkBookOpen("C:\Users\schuec1\Desktop\Peoria 2017 Media\Live Analysis\Live_Analysis.xlsx")
If file_status = False Then
Set oXL = CreateObject("Excel.Application")
Set oWb = oXL.Workbooks.Open(FileName:="C:\Users\schuec1\Desktop\Peoria 2017 Media\Live Analysis\Live_Analysis")
Else
Set oXL = Excel.Application
Set oWb = ActiveWorkbook
End If
Dim sld_no As Long
Dim course As String
Dim sld_offset As Long
Dim teamno As Long
Dim lead_sld As Long
Dim cntry As String
Dim pic_flag As Shape
Dim row_space As Shape
Dim team_range As Range
Dim school As String
Dim time_car As Double
Dim diff As Double
Dim time_one As Double
Dim pos As Long
Dim dist As Double
Dim dist_one As Double
Dim pplayout As CustomLayout
sld_no = SSW.View.CurrentShowPosition
'Acceleration leaderboard
If sld_no = 1001 Then
lead_sld = sld_no
With ActivePresentation
.Slides(lead_sld).Delete
End With
Debug.Assert lead_sld <> sld_no
Set oSld = ActivePresentation.Slides.AddSlide(lead_sld, GetLayout("accel"))

Resources