Vlookup in Excel Macro
Domanda
Ho creato un modulo in Excel che prende input dagli utenti e salva lo stesso in foglio2.Ho un account Named ComboBox da cui gli utenti selezionano il nome dell'account.Tuttavia ogni account avrà un ID univoco associato ad esso.Non voglio esporre questo ID agli utenti finali ma allo stesso tempo voglio che l'ID corrispondente all'account selezionato in foglio2.
Sto cercando di eseguire un Vlookup per cercare l'ID dell'account selezionato.
Ho configurato i valori dell'account in foglio3.
Example: Column A ColumnB Account1 Id12345 Account2 Id23456 Account3 Id34567.
Il mio codice in Excel Macro sembra qualcosa di simile.
Private Sub Save_Click()
Dim RowCount As Long
Dim myValue as String
RowCount = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count
With Worksheets("Sheet2").Range("A1")
.Offset(RowCount, 0).Value = Me.Account.Value
myValue = WorksheetFunction.VLookup(Range("A2"), Range("Sheet3!G1:G14"), 2, False)
.
Non sono sicuro del perché non funziona.Qualsiasi suggerimento sarà molto apprezzato.
Grazie,
Soluzione
Prova questo:
Private Sub Save_Click()
Dim RowCount As Long
Dim myValue As Variant
Dim Sh2 As Worksheet, Sh2 As Worksheet
Dim RefRange As Range
With ThisWorkbook
Set Sh2 = .Sheets("Sheet2")
Set Sh3 = .Sheets("Sheet3")
End With
RowCount = Sh2.Range("A1").CurrentRegion.Rows.Count
Set RefRange = Sh3.Range("G1:H14") '--Change as necessary.
Sh2.Range("A1").Offset(RowCount, 0).Value = Me.Account.Value
On Error GoTo myValueErrHandle
myValue = WorksheetFunction.VLookup(Sh2.Range("A2").Value, RefRange, 2, False)
'--More code, etc etc.
myValueErrHandle:
If Err.Number = 1004 Then
MsgBox "No match using VLOOKUP."
End If
Exit Sub
End Sub
.
Il più possibile, qualifica tutto ciò che puoi e usa il codice succinto ma significativo.Non usare Range("A2")
se vuoi quello che è dentro.Usa .Value
Poiché questa è la migliore pratica.Per quanto posso vedere, non c'è niente di sbagliato.Ho anche aggiunto una gestione Error 1004
per nessuna corrispondenza.Infine, nota che ho cambiato myValue
in un Variant
, solo per coprire le basi.
Faccelo sapere se funziona.
Altri suggerimenti
prova questo?: Scusa troppo a lungo per inserire un commento:
With Worksheets("Sheet2")
.Range("A1").Offset(RowCount, 0).Value = Me.Account.Value
myValue = WorksheetFunction.VLookup(.Range("A2"), Sheeet3.Range("G1:H14"), 2, False)"
End With
.
Solo forse, quindi provalo.
Sub Lookup()
Dim Emp As String
Dim Lookup_Range As Range
Dim Age As Single
Emp = "Jitu"
Set Lookup_Range = Range("A1:B8")
Age = Application.WorksheetFunction.VLookup(Emp, Lookup_Range, 2, False)
MsgBox "Age is : $ " & Age
End Sub
.
Tabella: EMP ETÀ Bibhash 22. Rahul 22. Abhisek 23. jitu 21. Sujit 24. Tinku 25. rudra 26