Invalid property value vba excel

 

СердЖиГ

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

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

Добрый день, Уважаемые эксперты!  

  У меня есть форма с немаленьким кодом, и при выполнении определённых действий появляется сообщение «Invalid Property Value».  
Каким образом можно определить по какой причине она появляется и как сделать, чтобы вместо этого сообщения выходил мой Msgbox?  
К сожалению, форму или пример пока не могу выложить, может кто сможет меня направить в правильное русло?  

  Заранее благодарен за помощь!!!

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

«Invalid Property Value» означает, что Вы пытаетесь присвоить объекту значение, которое он не поддерживает. Например: UserForm1.Width = -100  

  Чтобы отследить я бы посоветовал пошагово пройти весь код — так будет вернее.  
Или при помощи On error Goto    
msgbox(«Код ошибки» & Err.Number) — узнать номер ошибки(ошибок) и сделать обработчик ошибок.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

СердЖиГ

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

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

The_Prist, действительно, Вы правы.  
У меня есть два свзанных (по спискам) comboboxа, при выборе определённого варианта в combobox1 присваивается определённый список combobox2, и в этом списке нет пустого значения. И если зайти в combobox2 и не выбрав ни одного варианта выйти, мы присвоим combobox2 значение пусто, а так как в списке пусто нет, вот ошибка и появляется.  
Отсюда вопросы:    
1) как сделать, чтобы нельзя было не выбрать ни одного варианта в combobox2?  
2) как сделать, чтобы не появлялась ошибка (по-подробнее, я в этом не очень шарю).  
Помогите, кто чем может!  
Спасибо!

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Поставьте условие(вроде такого). Писал на коленке,так что…  
If ComboBox2.Value <> «» or Not isEmpty(ComboBox2.Value) Then  
ComboBox1.Value = ComboBox2.Value  
 Else  
msgBox(«Не выбрано ни одного значения!»)  
end if

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

СердЖиГ

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

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

{quote}{login=СердЖиГ}{date=18.11.2008 11:53}{thema=немного понял в чём дело}{post}The_Prist, действительно, Вы правы.  
У меня есть два свзанных (по спискам) comboboxа, при выборе определённого варианта в combobox1 присваивается определённый список combobox2, и в этом списке нет пустого значения. И если зайти в combobox2 и не выбрав ни одного варианта выйти, мы присвоим combobox2 значение пусто, а так как в списке пусто нет, вот ошибка и появляется.  
Отсюда вопросы:    
1) как сделать, чтобы нельзя было не выбрать ни одного варианта в combobox2?  
2) как сделать, чтобы не появлялась ошибка (по-подробнее, я в этом не очень шарю).  
Помогите, кто чем может!  
Спасибо!{/post}{/quote}  

    Причём мне не совсем понятно, почему присваивается пустое значение, т.к. MatchRequired = True, то есть вводимый пользователем текст может стать значением элемента, лишь когда он совпадает с одним из элементов списка.

 

У меня похожая проблема. В Combobox постаил MatchRequired=True.  
Если что нибудь напечатать в Combobox после чего попытаться нажать Enter, Tab или просто перевести курсор появляется ошибка Invalid Property Value.    
Пытался перехватить с помощью On error Goto в событии Change, сообщение On error Goto появляется при любом наборе символа, а если нажать Enter, Tab или просто перевести курсоропять пояляется Invalid Property Value.    
Подскажите как перехватить это сообщение, что бы сообщить пользователю что он ввел данные не из списка ???

 

При MatchRequired = true в ComboBox можно вводить либо допустимые значения, либо выходить по  <ESC> не меняя текущего значения.  

  То есть фактически это выпадающийсписок с остановом, почему б его и не использовать?  
В чём смысл разрешать ввод буковок если буковки должны быть вполне определёнными?  

  По вопросу  
может поможет,  
но можь и нет:  

  Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)  
If ComboBox1.MatchFound = True Then  
Exit Sub  
Else  
MsgBox ComboBox1.Value & «Ошибка Ввода! Требуется значение из списка или <ESC>!»  
Cancel = True  
End If  
End Sub

 

что ета я играт call of duty 4multipleyr cod recon toll тож какай та invalid property valiu  помагети мне

 

harry

Гость

#9

14.06.2012 21:16:30

что ета Run tame eror 380 invalid property valu

I’m trying the following code from excel vba tutorial but it fails: the ProgressBat is not updating, plus UserForm1.ProgressBar1.Value = UserForm1.ProgressBar1.Value + 1 line gets highlited with an error `Run-time error 380. Invalid property value».

Sub ShowProgressBar()
    Dim lAllCnt As Long
    Dim rc As Range

    lAllCnt = Selection.Count

    UserForm1.Show
    UserForm1.ProgressBar1.Min = 1
    UserForm1.ProgressBar1.Max = lAllCnt

    For Each rc In Selection

        UserForm1.ProgressBar1.Value = UserForm1.ProgressBar1.Value + 1

    Next

    Unload UserForm1
End Sub

What may be wrong?

asked Jun 27, 2017 at 13:18

Ans's user avatar

3

That is because you are exceeding the max value. Try this

For Each rc In Selection
    If UserForm1.ProgressBar1.Value < UserForm1.ProgressBar1.Max Then
        UserForm1.ProgressBar1.Value = UserForm1.ProgressBar1.Value + 1
    End If
Next

BTW I guess you forgot to mention vbModeless after UserForm1.Show

Explanation

When you set a minimum or maximum value of a progressbar then you cannot assign a value to it which doesn’t fall in the range. For example, if the minimum value = 1 and maximum value = 5 then the moment you assign a value which is less than 1 and greater than 5, you will get an error.

This is the tested code

Sub ShowProgressBar()
    Dim lAllCnt As Long
    Dim rc As Range

    lAllCnt = Selection.Count

    With UserForm1
        .Show vbModeless

        With .ProgressBar1
            .Min = 1
            .Max = lAllCnt

            For Each rc In Selection
                If .Value < .Max Then
                    .Value = .Value + 1
                End If
            Next
        End With
    End With

    '~~> I have uncommented it so that you can see the
    '~~> Userform with the progress bar with it's values
    'Unload UserForm1
End Sub

answered Jun 27, 2017 at 13:25

Siddharth Rout's user avatar

Siddharth RoutSiddharth Rout

146k17 gold badges206 silver badges250 bronze badges

8

As already mentioned, you should try to take a look at the min and max values. I have done it in a separate function. In general, it is probably a good idea to wait between the iterations, to see the progress bar updating.

Option Explicit

Sub ShowProgressBar()

    Dim lAllCnt         As Long
    Dim rc              As Range

    lAllCnt = Selection.Count

    UserForm1.Show vbModeless
    UserForm1.ProgressBar1.Min = 1
    UserForm1.ProgressBar1.Max = lAllCnt

    For Each rc In Selection
        UserForm1.ProgressBar1.Value = fnBigOrSmallIncrement(UserForm1.ProgressBar1.Value, 1, lAllCnt)
        Application.Wait Now + #12:00:01 AM#
    Next

    Unload UserForm1

End Sub

Public Function fnBigOrSmallIncrement(lngCurrent As Long, lngMin As Long, lngMax As Long) As Long

    fnBigOrSmallIncrement = lngCurrent + 1

    If fnBigOrSmallIncrement < lngMin Then fnBigOrSmallIncrement = lngMin
    If fnBigOrSmallIncrement > lngMax Then fnBigOrSmallIncrement = lngMax

End Function

In general, if you are well familiar with Object Oriented Programming and you want to make your code better, try to rebuild the whole form as a class.

Graham's user avatar

Graham

7,33918 gold badges59 silver badges84 bronze badges

answered Jun 27, 2017 at 13:33

Vityata's user avatar

VityataVityata

42.4k8 gold badges55 silver badges98 bronze badges

I am not sure how Your progress form looks and what type of code You are using (maybe paste a link?) but when I used the progress bar I only changed the width property of the user form bar instead of its value, e. g. like here http://www.excel-easy.com/vba/examples/progress-indicator.html.

answered Jun 27, 2017 at 13:28

Mikisz's user avatar

MikiszMikisz

4044 silver badges20 bronze badges

1

I’ve built this userform and whenever I click on the command button to unload the entered information into the spreadsheet I get the «Invalid Property Value» message and the userform freezes with all the information cleared except for the listbox choices
which are still highlighted.

Can’t seem to figure out why this message is coming up and why it is preventing the form from clearing for the next entry. Am I missing code for the listboxes that would allow for the information to clear when I unload the form?

Here’s the code that I have used, courtesy of Contexture and Bernie Dietrick.

Private Sub cmdAdd_Click()
Dim lRow As Long
Dim lPart As Long
Dim ws As Worksheet
Set ws = Worksheets(«Database»)

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

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

‘copy the data to the database
With ws
  .Cells(lRow, 1).Value = Me.cboCategory.Value
  .Cells(lRow, 2).Value = Me.cboTitle.Value
  .Cells(lRow, 3).Value = Me.txtFirstName.Value
  .Cells(lRow, 4).Value = Me.txtLastName.Value
  .Cells(lRow, 5).Value = Me.txtHomeAddress.Value
  .Cells(lRow, 6).Value = Me.txtCity.Value
  .Cells(lRow, 7).Value = Me.txtPostalCode.Value
  .Cells(lRow, 8).Value = Me.txtDOB.Value
  .Cells(lRow, 9).Value = Me.txtContactNo.Value
  .Cells(lRow, 10).Value = Me.txtWorkNo.Value
  .Cells(lRow, 11).Value = Me.txtCellNo.Value
  .Cells(lRow, 12).Value = Me.txtemail.Value
  .Cells(lRow, 13).Value = Me.cboMeansContact.Value
  .Cells(lRow, 14).Value = Me.cboContactTime.Value
  .Cells(lRow, 15).Value = Me.cbodriverslicense.Value
  .Cells(lRow, 16).Value = Me.cboOwnCar.Value
  .Cells(lRow, 17).Value = Me.ListBoxHowDidYouHear.Value
   Dim strSelected As String
    strSelected = «»
    Dim i As Integer
    With Me.ListBoxHowDidYouHear
        For i = 0 To .ListCount — 1
            If .Selected(i) = True Then
                If strSelected = «» Then
                    strSelected = .List(i)
                Else
                    strSelected = strSelected & «, » & .List(i)
                End If
            End If
        Next i
    End With

    .Cells(lRow, 17).Value = strSelected ’17th column!
  .Cells(lRow, 18).Value = Me.txtOtherHearKalein.Value
  .Cells(lRow, 19).Value = Me.txtCurrentEmployment.Value
  .Cells(lRow, 20).Value = Me.txtNameEmployer.Value
  .Cells(lRow, 21).Value = Me.cboSelfEmployed.Value
  .Cells(lRow, 22).Value = Me.txtNameBusiness.Value
  .Cells(lRow, 23).Value = Me.txtNatureSelfEmployment.Value
  .Cells(lRow, 24).Value = Me.txtCurrentAffiliations.Value
  .Cells(lRow, 25).Value = Me.txtNotesAffiliations.Value
  .Cells(lRow, 26).Value = Me.ListBoxReasonVolunteer.Value
    strSelected = «»
    With Me.ListBoxReasonVolunteer
        For i = 0 To .ListCount — 1
            If .Selected(i) = True Then
                If strSelected = «» Then
                    strSelected = .List(i)
                Else
                    strSelected = strSelected & «, » & .List(i)
                End If
            End If
        Next i
    End With

    .Cells(lRow, 26).Value = strSelected ’26th column!
   .Cells(lRow, 27).Value = Me.txtOtherReasonVolunteer.Value
   .Cells(lRow, 28).Value = Me.cboSkills1.Value
   .Cells(lRow, 29).Value = Me.cboSkills2.Value
   .Cells(lRow, 30).Value = Me.txtOtherSkills.Value
   .Cells(lRow, 31).Value = Me.cboInquiringPosition.Value
   .Cells(lRow, 32).Value = Me.cboResume.Value
   .Cells(lRow, 33).Value = Me.txtNotesSkills.Value
   .Cells(lRow, 34).Value = Me.cboVolunteerAreas1.Value
   .Cells(lRow, 35).Value = Me.cboVolunteerAreas2.Value
   .Cells(lRow, 36).Value = Me.txtOtherVolunteerAreas.Value
   .Cells(lRow, 37).Value = Me.cboHospiceCareVolunteer.Value
   .Cells(lRow, 38).Value = Me.cboCompletedTraining.Value
   .Cells(lRow, 39).Value = Me.txtTrainingWhereWhen.Value
   .Cells(lRow, 40).Value = Me.cboInterestedTraining.Value
   .Cells(lRow, 41).Value = Me.cboAvailability.Value
   .Cells(lRow, 42).Value = Me.cboDaysAvailable1.Value
   .Cells(lRow, 43).Value = Me.cboDaysAvailable2.Value
   .Cells(lRow, 44).Value = Me.ListBoxTimeAvailable.Value
    strSelected = «»
    With Me.ListBoxTimeAvailable
        For i = 0 To .ListCount — 1
            If .Selected(i) = True Then
                If strSelected = «» Then
                    strSelected = .List(i)
                Else
                    strSelected = strSelected & «, » & .List(i)
                End If
            End If
        Next i
    End With

    .Cells(lRow, 44).Value = strSelected ’44th column!
   .Cells(lRow, 45).Value = Me.cboReceiveUpdates.Value
   .Cells(lRow, 46).Value = Me.cboReceiveDonorInfo.Value
   .Cells(lRow, 47).Value = Me.txtGeneralNotes.Value
   .Cells(lRow, 48).Value = Me.txtSpousePartner.Value
   .Cells(lRow, 49).Value = Me.txtEmergencyContact.Value
   .Cells(lRow, 50).Value = Me.txtEmergencyNumber.Value
   .Cells(lRow, 51).Value = Me.cboMinor.Value
   .Cells(lRow, 52).Value = Me.cboParentalConsent.Value

      
   End With

‘clear the data
Me.cboCategory.Value = «»
Me.cboTitle.Value = «»
Me.txtFirstName.Value = «»
Me.txtLastName.Value = «»
Me.txtHomeAddress.Value = «»
Me.txtCity.Value = «»
Me.txtPostalCode.Value = «»
Me.txtDOB.Value = «»
Me.txtContactNo.Value = «»
Me.txtWorkNo.Value = «»
Me.txtCellNo.Value = «»
Me.txtemail.Value = «»
Me.cboMeansContact.Value = «»
Me.cboContactTime.Value = «»
Me.cbodriverslicense.Value = «»
Me.cboOwnCar.Value = «»
Me.ListBoxHowDidYouHear.Value = «»
Me.txtOtherHearKalein.Value = «»
Me.txtCurrentEmployment.Value = «»
Me.txtNameEmployer.Value = «»
Me.cboSelfEmployed.Value = «»
Me.txtNameBusiness.Value = «»
Me.txtNatureSelfEmployment.Value = «»
Me.txtCurrentAffiliations.Value = «»
Me.txtNotesAffiliations.Value = «»
Me.ListBoxReasonVolunteer.Value = «»
Me.txtOtherReasonVolunteer.Value = «»
Me.cboSkills1.Value = «»
Me.cboSkills2.Value = «»
Me.txtOtherSkills.Value = «»
Me.cboInquiringPosition.Value = «»
Me.cboResume.Value = «»
Me.txtNotesSkills.Value = «»
Me.cboVolunteerAreas1.Value = «»
Me.cboVolunteerAreas2.Value = «»
Me.txtOtherVolunteerAreas.Value = «»
Me.cboHospiceCareVolunteer.Value = «»
Me.cboCompletedTraining.Value = «»
Me.txtTrainingWhereWhen.Value = «»
Me.cboInterestedTraining.Value = «»
Me.cboAvailability.Value = «»
Me.cboDaysAvailable1.Value = «»
Me.cboDaysAvailable2.Value = «»
Me.ListBoxTimeAvailable.Value = «»
Me.cboReceiveUpdates.Value = «»
Me.cboReceiveDonorInfo.Value = «»
Me.txtGeneralNotes.Value = «»
Me.txtSpousePartner.Value = «»
Me.txtEmergencyContact.Value = «»
Me.txtEmergencyNumber.Value = «»
Me.cboMinor.Value = «»
Me.cboParentalConsent.Value = «»
Me.cboCategory.SetFocus

End Sub

Private Sub cmdClose_Click()
Unload Me
End Sub

Permalink

Cannot retrieve contributors at this time

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

Invalid property value (Error 380) [1 of 2]

vblr6.chm380

vblr6.chm380

office

d7e48f4d-5dae-d62d-498b-282516540f8f

06/08/2017

medium

Most properties only accept values of a certain type, within a certain range. This error has the following cause and solution:

  • An inappropriate value has been assigned to a property. See the property’s Help topic to determine what types and range of values are appropriate for the property.

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

[!includeSupport and feedback]

  • #2

marsland,
Can you post your code, and let us know what the old sheet and new sheet names are.

Cal

  • #3

theres too much of it to be honest!!!!!

the old name was just ‘sheet1’ and the new name i want is ‘home’

  • #4

OK then,

when i try and change it in the vba editor in the properties box.

This statement doesn’t make a lot of sense to me? You wouldn’t change the sheet name in a properties box, it would be in all the references to that sheet within your code?

ie.

Sheets(«Sheet1»).????
Would change to
Sheets(«Home»).????

What object are you changing the properties box of?

Cal

  • #5

Yeeah — ive tried changing all the references throughout my code — just like you implied and then also, in the editor — in the «properties — sheet 1» box (its always on the LHS of my page — not sure about other users!!) on the ‘Name’ property, ive tried typing in home but it refuses it.

  • #6

marsland,
The value you are trying to change in the vba editor shouldn’t be a issue. As soon as you change the name on your workbook, it should update in the vba editor. It should say something like Sheet1 (Home). If not then your sheetname change didn’t work correctly(I’ve never seen it not change).
Your update of the references tells me that you should be referencing the new named sheet fine. Do you run into a code error when you run it? If so, post the line of code that errors. If not, what’s it doing wrong?
One other thing to check. Make sure your sheet name doesn’t have any extra spaces. Try changing the sheet name again, and see what’s highlighted. It could be you added a space by mistake, so it’s looking for sheets(«Home «) instead of sheets(«Home»).

HTH
Cal

  • #7

Thanks Cal,

Finally got it sorted — you were right with the spelling! (She says shamefully) why do such trivial things always mess up days worth of code?!?!?!

  • #8

:biggrin: The only problem is you don’t realize it’s a simple problem till you’ve tried all the difficult things first.

Понравилась статья? Поделить с друзьями:
  • Interest payments in excel
  • Invalid pointer operation что означает word
  • Intercept в excel это
  • Invalid outside procedure vba excel
  • Intercept excel на русском