2016-10-06 38 views
0

我希望在VBA中的.Match函數中使用選定列表框項目的字符串值 - 我需要將值'1'輸入到行中其中選擇的值與特定列上的「A:A」列中的值匹配。從Excel中的參考值列表項在VBA中的匹配功能

我以爲我能做的就是爲選定的ListBox項目使用.value參數,但是這似乎要麼出錯或給我一個布爾響應,這不是我所追求的(I是在物品的實際字符串值之後)。

我已經遍歷所有項目以將Selected參數設置爲True,然後我逐個遍歷列表以向正確的範圍添加'1'。

這裏是我想會的工作代碼(但是沒有,它拋出的「運行時錯誤‘13’:類型不匹配」的錯誤。這大概是下降到。價值不是作爲一個字符串

For x = 0 To Me.CreditsEmployeesListBox.ListCount - 1 
Me.CreditsEmployeesListBox.Selected(x) = True 
Next 

For i = 0 To Me.CreditsEmployeesListBox.ListCount - 1 
If Me.CreditsEmployeesListBox.Selected(i) = True Then 
    employeeRow = WorksheetFunction.Match(Me.CreditsEmployeesListBox(i).Value, IndexSheet.Range("A:A"), 0) 
    IndexSheet.Range(Cells(employeeRow, showCodeColumn).Address).Value = 1 
End If 
Next 

它的錯誤出在「employeeRow = ...」線在這裏,我主要想問問它:

employeeRow = WorksheetFunction.Match(<value of the currently referenced ListBox item>,IndexSheet.Range("A:A"),0) 

這可能與VBA或我要對這個錯誤的方式?

Tha NKS 馬特

+0

如果找不到匹配的當前值,它會通過錯誤並停止代碼。使用'Application'而不是'WorksheetFunction'。您將需要在循環內聲明'employeeRow'作爲變體。然後你需要在賦值之前測試它是否是錯誤:'IF not IsError(employeeRow)then' –

+1

@ScottCraner'If Not IsError(...'?我確定這是一個錯字,你試圖寫如果IsNumeric(...';) –

+0

@DirkReichel或者可以工作,但是,你的輸入更少,邏輯更簡單 –

回答

0

爲「混合型」的答案(因爲有不止一個的問題)試試這個:

For x = 0 To Me.CreditsEmployeesListBox.ListCount - 1 
    Me.CreditsEmployeesListBox.Selected(x) = True 
Next 

Dim employeeRow As Variant 
For i = 0 To Me.CreditsEmployeesListBox.ListCount - 1 
    If Me.CreditsEmployeesListBox.Selected(i) = True Then 
    employeeRow = Application.Match(Me.CreditsEmployeesListBox.List(i), IndexSheet.Columns(1), 0) 
    If IsNumeric(employeeRow) Then IndexSheet.Cells(employeeRow, showCodeColumn).Value = 1 
    End If 
Next 

這也應該避免VBA的錯誤。

如果還有問題,請提問:)

+0

謝謝Dirk,只是增加了'CreditsEmployeesListBox.List(i)'到獲取列表框項目的字符串值已經完成了。對於IsNumeric錯誤捕獲,列表框中的條目從IndexSheet本身填充,所以總會有一個歸於該項目的行號。減! – mhurstsmith

+0

歡迎您:) –