Как в vba excel method or data member not found

I have been using this excel program for several months without issues. suddenly a couple days ago it started to throw this error. On sheet named «Input» I will double click a cell in column «A» which will create a drop down box that will fill with data from the «Data» sheet. I start typing and then I select the data to add to the cell. Now when I click the cell and get an error message «Compile Error — Method or data member not found». Here is my block of code and the error is showing near the bottom highlighting «Me.TempCombo.Activate».

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim str As String
    Dim cboTemp As OLEObject
    Dim ws As Worksheet
    Set ws = ActiveSheet

    If Target.Column = 1 And Target.Row > 12 And Target.Row <> HRRow And Target.Row <> HRRow - 1 Then

        lRow = Sheets("Data").Range("A65536").End(xlUp).Row
        Set cboTemp = ws.OLEObjects("TempCombo")
          On Error Resume Next

          With cboTemp
          'clear and hide the combo box
            .ListFillRange = ""
            .LinkedCell = ""
            .Visible = False
          End With
        On Error GoTo errHandler
          'If Target.Validation.Type = 3 Then
            'if the cell contains a data validation list
            Cancel = True
            Application.EnableEvents = False
            'get the data validation formula
            'str = Target.Validation.Formula1
            'str = Right(str, Len(str) - 1)
            str = "=Data!A2:A" & lRow

            With cboTemp
              'show the combobox with the list
              .Visible = True
              .Left = Target.Left
              .Top = Target.Top
              .Width = Target.Width + 5
              .Height = Target.Height + 5
              .ListFillRange = str
              .LinkedCell = Target.Address
            End With
            'cboTemp.Activate
            Me.TempCombo.Activate
            'open the drop down list automatically
            Me.TempCombo.DropDown

      End If

errHandler:
      Application.EnableEvents = True
      Exit Sub
End Sub

I tried several things and for the life of me I cannot figure out what changed.
Any help will be appreciated. Thank you.

Kritner's user avatar

Kritner

13.4k10 gold badges50 silver badges72 bronze badges

asked Dec 10, 2014 at 14:26

Scott's user avatar

2

I ran into the same error and was able to solve it as Rory suggested. I searched my machine for *.exd files and found a few. The issue was solved for me after removing C:Users<username>AppDataLocalTempExcel8.0MSForms.exd…the others seemed to be unrelated to the ActiveX controls in Excel.

answered Dec 29, 2014 at 21:13

Tom's user avatar

Looks like the code came from an example like this: http://www.contextures.com/xlDataVal10.html

except your code has commented out the line which activates the cboTemp combobox. Your code is attempting to access the TempCombo attribute of the worksheet (which I don’t think exists). Uncomment 'cboTemp.Activate on the line above the highlighted error line.

answered Dec 10, 2014 at 14:39

Lefty's user avatar

LeftyLefty

4263 silver badges10 bronze badges

I had the same problem, my code broke this morning. Fortunately, I recalled that I ran Windows Update this weekend. I performend a system restore (earliest available restore point was 8th of december), and now the problem is gone.

I never did understand the panicy server guys who were always making backups and spending a whole lot of time testing before/after system updates, in all my years I never experienced any problems. Now I sure figured out what they were talking about. Lesson learnt. I’ll try running win update again in a few months, hopefully MS has solved the problem by then.

Best of luck

answered Dec 15, 2014 at 19:18

Fossie's user avatar

1

 

fafelbko

Пользователь

Сообщений: 9
Регистрация: 06.08.2018

#1

06.09.2018 12:14:43

Добрый день коллеги.
Есть файл с двумя листами, на первом листе в любом столбце может появиться столбец «Код модели».
Мы находим этот столбец и с помощью ВПР сравниваем с базой на втором листе.
Затем подставляем в закладку в Worde.
VB почему-то ругается на Range(«H2:I27») и пишет «Method or data member not found»
Посоветуйте, как избежать этой ошибки?

Код
If Not Cells.Find(What:="Код модели") Is Nothing Then
Cells.Find(What:="Код модели").Activate
E_name = ActiveSheet.Cells(i, ActiveCell.Column).Text 
Sal = Application.WorksheetFunction.VLookup(E_name, Sheet1.Range("H2:I27"), 2, False)
.bookmarks("bookmark_14").Range.Text = Sal
    Else: MsgBox "Не найден столбец 'код модели'; обработка прервана", vbExclamation
        Exit Sub
End If
 

StoTisteg

Пользователь

Сообщений: 441
Регистрация: 07.05.2018

#2

06.09.2018 12:20:39

Код
With Sheet1
Sal = Application.WorksheetFunction.VLookup(E_name, .Range(.Cells(2,8),.Cells(27,9)), 2, False)
End With

Ячейки должны быть с того же листа, что и включающий их диапазон.

Изменено: StoTisteg06.09.2018 12:20:46

 

fafelbko

Пользователь

Сообщений: 9
Регистрация: 06.08.2018

Внёс ваше исправление, но точно такая же ошибка «Method or data member not found» и ругается теперь на .Cells

 

ivanok_v2

Пользователь

Сообщений: 712
Регистрация: 19.08.2018

#4

06.09.2018 12:31:04

Цитата
fafelbko написал:
Sheet1

у вас точно так название?

 

StoTisteg

Пользователь

Сообщений: 441
Регистрация: 07.05.2018

А переменная Sheet1 у вас вообще какого типа? И где ей присваивается значение?

 

Hugo

Пользователь

Сообщений: 23252
Регистрация: 22.12.2012

Подозреваю что нет объекта Sheet1. Файла нет (да и всего кода нет), поэтому остаётся только подозревать.

 

StoTisteg

Пользователь

Сообщений: 441
Регистрация: 07.05.2018

Hugo, вот и я подозреваю, что её нет и имеется в виду Worksheets(«Sheet1»)…

 

StoTisteg

Пользователь

Сообщений: 441
Регистрация: 07.05.2018

А ещё я в упор не понимаю, нафига нужен ВПР там, где работают Find и Offset…

Изменено: StoTisteg06.09.2018 12:58:36

 

fafelbko

Пользователь

Сообщений: 9
Регистрация: 06.08.2018

#9

06.09.2018 12:46:02

Коллеги, прошу прощения, не дописал.
Обьявил

Код
Dim Worksheets("Sheet1") As Object

Ругается Type mismatch
Могу предоставить весь файл

Прикрепленные файлы

  • Рассылка_дилерам.xlsm (96.16 КБ)

 

ivanok_v2

Пользователь

Сообщений: 712
Регистрация: 19.08.2018

#10

06.09.2018 12:48:42

Цитата
fafelbko написал:
Dim Worksheets(«Sheet1») As Object

fafelbko, у вас есть понятия работы кода?
так как ето говорит совсем обратное

 

fafelbko

Пользователь

Сообщений: 9
Регистрация: 06.08.2018

Не совсем. Не могли бы подсказать?

 

StoTisteg

Пользователь

Сообщений: 441
Регистрация: 07.05.2018

fafelbko, знаете, Вам нужно взять справочник и почитать там, что такое переменная, что означает Worksheets(«Sheet1») и понять, почему написанное Вами — мягко говоря, ерунда.

 

Юрий М

Модератор

Сообщений: 60581
Регистрация: 14.09.2012

Контакты см. в профиле

#13

06.09.2018 13:09:53

fafelbko, весь код не смотрел, но переменную Вы объявляете неправильно. Нужно примерно так:

Код
Dim Sht As Worksheet
Set Sht = Worksheets("Лист1")


 

_Boroda_

Пользователь

Сообщений: 1496
Регистрация: 27.07.2013

Контакты см. в профиле

#14

06.09.2018 13:14:39

Код
Sal = Application.WorksheetFunction.VLookup(E_name, Worksheets("Лист1").Range("H2:I27"), 2, False)

Изменено: _Boroda_06.09.2018 13:14:45

Скажи мне, кудесник, любимец ба’гов…

 

fafelbko

Пользователь

Сообщений: 9
Регистрация: 06.08.2018

#15

06.09.2018 14:05:38

Коллеги. Прошу простить мою некомпетентность.
Спасибо большое в помощи с моим вопросом, всё работает!

  • Remove From My Forums
  • Question

  • Hello,

    Here is my code to deselect or clear all values in all Listboxes:

    Private Sub CommandButton3_Click()

        Dim Ctrl As Control

        Dim i As Long

        For Each Ctrl In Me.Controls

            If TypeName(Ctrl) = «ListBox» Then

               
    With Ctrl

                   
    For i = 0 To .ListCount — 1

                       
    .Selected(i) = False

                   
    Next i

               
    End With

            End If

        Next Ctrl

    End Sub

    I am getting error: Mothod or data member not found. 

    Can anybody help me?

    Thanks in anticipation

    • Edited by

      Friday, June 6, 2014 12:50 PM

Answers

  • Hi,

    I can’t reproduce this issue.

    I made a test for you in Excel 2013.

    I created an Excel userform as below:

    'Fill data
    Private Sub CommandButton1_Click()
        ListBox1.AddItem "1"
        ListBox1.AddItem "2"
        ListBox1.AddItem "3"
        ListBox1.MultiSelect = fmMultiSelectMulti
        ListBox1.Selected(1) = True
        ListBox1.Selected(2) = True
        
        ListBox2.AddItem "4"
        ListBox2.AddItem "5"
        ListBox2.AddItem "6"
        ListBox2.MultiSelect = fmMultiSelectMulti
        ListBox2.Selected(0) = True
        ListBox2.Selected(1) = True
    End Sub
    
    'clear selection
    Private Sub CommandButton2_Click()
        Dim Ctrl As Control
        Dim i As Long
        For Each Ctrl In Me.Controls
            If TypeName(Ctrl) = "ListBox" Then
                 With Ctrl
                    For i = 0 To .ListCount - 1
                        .Selected(i) = False
                    Next i
                 End With
            End If
        Next Ctrl
    End Sub

    The code works with no issue:

    Is there anything I missed?

    What is your Excel version? Where did you type the code?


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Proposed as answer by
      Paul Eugin Francis
      Tuesday, June 10, 2014 10:24 AM
    • Marked as answer by
      George Hua
      Friday, June 13, 2014 9:16 AM

  • Ya. I realized the mistake and i changed the code. Still it was not working then i placed all controls on new worksheet now this code is working properly.

    Thanks a lot :)

    • Marked as answer by
      George Hua
      Friday, June 13, 2014 9:16 AM

You’re getting the error because showInputsDialog isn’t a member of the form, it’s a member of the module you’re calling it from. You should also be getting compiler errors on these two lines…

Call Initialize
Me.Show

…because you seem to be getting the module and form code mixed up.

That said, you’re overthinking this. A UserForm is a class module, and it can be stored in a variable (or in this case, in a With block), and can have properties. I’d add a Cancelled property to the form:

'In sportsUsrFrm
Option Explicit

Private mCancel As Boolean

Public Property Get Cancelled() As Boolean
    Cancelled = mCancel
End Property

Private Sub cmdCnl_Click()
    Me.Hide
    mCancel = True
End Sub

Private Sub cmdOK_Click()
    If Valid Then Me.Hide   '<-- You still need to implement `Valid`
End Sub

And then call it like this:

Sub sportUserForm()
    With New sportsUsrFrm
        .Show
        Dim sSport As String, sPreference As String
        If Not .Cancelled Then
            If .optBaseball.Value Then
                sSport = "Baseball"
            ElseIf .optBasketball.Value Then
                sSport = "Basketball"
            Else
                sSport = "Football"
            End If

            If .optTV.Value Then
                sPreference = "watch on TV"
            Else
                sPreference = "go to games"
            End If
            MsgBox "Your favorite sport is " & sSport & ", and you usually " _
                   & sPreference & "."
        Else
            MsgBox "Sorry you don't want to play."
        End If
    End With
End Sub

Comments

  • EDIT: To clarify, the code seen below is within a module and the UserForm is all contained within its own code.

    I have the following code. When I go to run it, Excel throws me a compile error: Method or data member not found and highlights the following piece of code: .showInputsDialog. I have no idea how to resolve this error.

    To give more information, the sub sportUserForm is supposed to call up a UserForm sportsUsrFrm. Any help with this issue is greatly appreciated.

    Option Explicit
    
    Sub sportUserForm()
    
    Dim sSport As String, sPreference As String
    
    If sportsUsrFrm.showInputsDialog(sSport, sPreference) Then
        MsgBox "Your favorite sport is " & sSport & ", and you usually " _
                & sPreference & "."
            Else
        MsgBox "Sorry you don't want to play."
    End If
    End Sub
    
    Public Function showInputsDialog(sSports As String, sPreference As String) As Boolean
    Call Initialize
    Me.Show
    If Not cancel Then
        If optBaseball.Value Then sSport = "Baseball"
            ElseIf optBasketball.Value Then sSport = "Basketball"
            Elss sSport = "Football"
        End If
    
        If optTV.Value Then sPreference = "watch on TV" _
            Else: sPreference = "go to games"
        End If
    
        showInputsDialog = Not cancel
        Unload Me
    End Function
    

    UserForm code for sportUsrFrm

    Option Explicit
    
    Private Sub cmdCnl_Click()
        Me.Hide
        cancel = True
    End Sub
    
    Private Sub cmdOK_Click()
    
        If Valid Then Me.Hide
        cancel = False
    End Sub
    

    UserForm image

    • What code is in what module? Is everything in the userform? I’d suggest taking a look at this example in documentation for a better approach to form handling.

    • @Comintern I have edited the OP to reflect your questions.

    • Can you add the code for sportsUsrFrm_Initialize?

    • @Comintern unless that’s code that has been added by default, I do not believe I have written any code for sportsUsrFrm_Initialize.

    • Is there any code in the UserForm at all?

    • @Comintern I’ve added any event handlers behind the UserForm and a picture of the UserForm itself.

Recents

Related

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Method or data member not found (Error 461)

vblr6.chm1000461

vblr6.chm1000461

office

10733744-502f-06b3-f0c6-5f039d017be4

06/08/2017

medium

The collection, object, or user-defined type doesn’t contain the referenced member. This error has the following causes and solutions:

  • You misspelled the object or member name. Check the spelling of the names and check the Type statement or the object documentation to determine what the members are and the proper spelling of the object or member names.

  • You specified a collection index that’s out of range. Check the Count property to determine whether a collection member exists. Note that collection indexes begin at 1 rather than zero, so the Count property returns the highest possible index number.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Feb 23rd, 2018, 11:45 AM


#1

BettyCrocker is offline

Thread Starter


New Member


«Method or Data Member Not Found» VBA issues in excel

Hi there,

I have no clue what I’m doing but I have copied some code and adjusted to try and fit my purposes but for some reason the first line in my code is causing an issue. I keep getting the error message of «Method or Data Member Not Found» and then when I go to de-bug it is highlighting the first line, which reads:

Private Sub cmdAdd_Click()

I am trying to make a form to add the details of a new supplier to a spreadsheet. I have downloaded the practice sheet and opened that up and it’s working fine, but for some reason it has an issue with the first line in my sheet.

I have deleted some .exd files as suggested in another post but this hasn’t done anything.

Microsoft Office 365, Excel Version 1801 (Build 9001.2171)

I have no idea what VBA version I m running or even how to check — I also have no idea about coding, I just want a form!! Is there a simpler way to make a form to enter into a list of suppliers?? This seems so so long winded…

Entire Code Text:

Private Sub cmdAdd_Click()
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets(«Suppliers»)

‘find first empty row in database
iRow = ws.Cells.Find(What:=»*», SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

‘check for a name
If Trim(Me.txtName.Value) = «» Then
Me.txtName.SetFocus
MsgBox «Please enter a supplier name»
Exit Sub
End If

‘copy the data to the database
‘use protect and unprotect lines,
‘ with your password
‘ if worksheet is protected
With ws
‘ .Unprotect Password:=»password»
.Cells(iRow, 1).Value = Me.txtName.Value
.Cells(iRow, 2).Value = Me.txtWebsite.Value
.Cells(iRow, 3).Value = Me.txtPhoneNo.Value
.Cells(iRow, 4).Value = Me.txtAccountNo.Value
.Cells(iRow, 5).Value = Me.txtEmail.Value
.Cells(iRow, 6).Value = Me.txtContact.Value
.Cells(iRow, 7).Value = Me.txtCategory.Value
.Cells(iRow, 8).Value = Me.txtOpened.Value
.Cells(iRow, 9).Value = Me.txtUsername.Value
.Cells(iRow, 10).Value = Me.txtPassword.Value
‘ .Protect Password:=»password»
End With

‘clear the data

Me.txtName.Value = «»
Me.txtWebsite.Value = «»
Me.txtPhoneNo.Value = «»
Me.txtAccountNo.Value = «»
Me.txtEmail.Value = «»
Me.txtContact.Value = «»
Me.txtCategory.Value = «»
Me.txtOpened.Value = «»
Me.txtUsername.Value = «»
Me.txtPassword.Value = «»
Me.txtName.SetFocus
End Sub


Feb 23rd, 2018, 05:37 PM


#2

Re: «Method or Data Member Not Found» VBA issues in excel

Hi BettyCrocker,
The highlight first line will be yellow to indicates error in routine.
If you scroll down the actual error line will be highlight too in blue.
which line is highlighted blue?


Feb 23rd, 2018, 08:57 PM


#3

Re: «Method or Data Member Not Found» VBA issues in excel

Is there a simpler way to make a form to enter into a list of suppliers??

this is simple, it may be possible to make the code shorter, but it may mean redesigning your form a bit

«Method or Data Member Not Found»

is this procedure (sub) actually in the code pane for the userform or in a general module? for the me keyword to be valid, the code would need to be in the form containing the textboxes, else you would need to specify the form by name

i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

come back and mark your original post as resolved if your problem is fixed
pete


Mar 9th, 2018, 08:15 AM


#4

BettyCrocker is offline

Thread Starter


New Member


Re: «Method or Data Member Not Found» VBA issues in excel

«which line is highlighted blue?[/QUOTE]»

‘check for a name
If Trim(Me

.txtName.Value) = «» Then
Me.txtName.SetFocus
MsgBox «Please enter a supplier name»
Exit Sub
End If

«.txtName»


Mar 9th, 2018, 08:18 AM


#5

BettyCrocker is offline

Thread Starter


New Member


Re: «Method or Data Member Not Found» VBA issues in excel

«is this procedure (sub) actually in the code pane for the userform or in a general module? for the me keyword to be valid, the code would need to be in the form containing the textboxes, else you would need to specify the form by name «

I have zero clue what you’re asking me sorry.


Mar 9th, 2018, 04:43 PM


#6

Re: «Method or Data Member Not Found» VBA issues in excel

the error indicates there is no object (textbox) with the name txtName in the me object

Me would refer to a userform, worksheet or other object and for it to be valid the code would have to be in the code module for that object
possibly replace the ME keyword, with the name of the textboxes container, like userform1.txtname

or post a sample workbook (zip first) with userform that demonstrates the problem

i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

come back and mark your original post as resolved if your problem is fixed
pete


Jun 9th, 2020, 06:33 AM


#7

kamalrana434 is offline


New Member


Re: «Method or Data Member Not Found» VBA issues in excel

Hi I am getting same error. Pls help

Sub Reset()

Dim iRow As Long

iRow = [Counta(Database!A:A)] ‘ idetifying the last row

With frmForm

.txtFinancialYear.Value = «»
.txtMonth.Value = «»
.txtProductionNos.Value = «»
.txtSquareFeet.Value = «»
.txtProductionValue.Value = «»


Jun 9th, 2020, 06:33 AM


#8

kamalrana434 is offline


New Member


Re: «Method or Data Member Not Found» VBA issues in excel

Hi I am getting same error. Pls help

Sub Reset()

Dim iRow As Long

iRow = [Counta(Database!A:A)] ‘ idetifying the last row

With frmForm

.txtFinancialYear.Value = «»
.txtMonth.Value = «»
.txtProductionNos.Value = «»
.txtSquareFeet.Value = «»
.txtProductionValue.Value = «»


Jun 9th, 2020, 04:06 PM


#9

Re: «Method or Data Member Not Found» VBA issues in excel

on which line does the error occur?
is this in access?

i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

come back and mark your original post as resolved if your problem is fixed
pete


Timon6969

0 / 0 / 0

Регистрация: 27.03.2018

Сообщений: 8

1

Excel

28.05.2018, 22:02. Показов 10044. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Ребят, не могу найти ошибку в коде:

Visual Basic
1
2
3
4
5
6
7
8
Private Sub UserForm_Initialize()
Region.AddItem "Áðåñòñêàÿ"
Region.AddItem "Ãðîäíåíñêàÿ"
Region.AddItem "Ìèíñêàÿ"
Region.AddItem "Âèòåáñêàÿ"
Region.AddItem "Ãîìåëüñêàÿ"
Region.AddItem "Ìîãèë¸âñêàÿ"
End Sub

Выбивает ошибку: method or data member not found
В чем проблема?



0



140 / 123 / 50

Регистрация: 10.11.2011

Сообщений: 620

28.05.2018, 23:03

2

Region-имя комбобокса



0



0 / 0 / 0

Регистрация: 27.03.2018

Сообщений: 8

29.05.2018, 17:09

 [ТС]

3

спасибо, все правильно делал, просто не заметил что имя Region для другого объекта указал)



0



140 / 123 / 50

Регистрация: 10.11.2011

Сообщений: 620

29.05.2018, 19:51

4

При последующем написании кода смотрите на ИМЯ



0



having some trouble adding s command button to a user form. Basically, I want the button to insert data into a new row on sheet1 with the fields set as below. However when testing the button I get a ‘Method or data member not found’ error message.

Not great with VBA, tried reading online but I am still confused as to what to do. Please help.

Private Sub CommandButton1_Click()

Dim LastRow As Long, ws As Worksheet

Set ws = Sheets("Sheet1")

LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1

ws.Range("A" & LastRow).Value = ComboBox1.Text
ws.Range("C" & LastRow).Value = TextBox1.Text
ws.Range("D" & LastRow).Value = ComboBox2.Text
ws.Range("F" & LastRow).Value = CheckBox2.Text
ws.Range("E" & LastRow).Value = CheckBox1.Text
ws.Range("H" & LastRow).Value = ListBox1.Text
ws.Range("G" & LastRow).Value = ListBox2.Text
ws.Range("I" & LastRow).Value = TextBox2.Text

End Sub

asked Sep 12, 2017 at 2:31

user767772's user avatar

2

Checkboxes don’t have a Text property. Use the Value property instead, e.g.:

ws.Range("F" & LastRow).Value = CheckBox2.Value

Note that this returns either «True» or «False». If you require anything else you need to do a check, for example:

ws.Range("F" & LastRow).Value = IIf(CheckBox2.Value,"Yes","No")

answered Sep 12, 2017 at 3:07

robinCTS's user avatar

robinCTSrobinCTS

4,3174 gold badges19 silver badges29 bronze badges

0

Понравилась статья? Поделить с друзьями:
  • Как в vba excel inputbox
  • Как в vba excel find
  • Как в vba excel exit
  • Как в powerpoint вставить файл word
  • Как в powerpoint вложить excel файл