VBA – 从用户的Combobox中复制文本,并将其粘贴到Excel工作表中

我是新的excel的VBA和我试图适应一些堆栈溢出find的解决scheme,但我仍然卡住!

我正在尝试在用户窗体中的combobox中使用选定的选项的文本将此选定的文本的行粘贴到Excel工作表。

下面的代码旨在select当前活动的用户窗体的combobox值“CboIncomesPatch”,并将此值粘贴到活动页的单元格“M8”中,然后循环粘贴,直到计数器达到数字总单元数为止。 单位总数是文本框值“TxtNumberOfUnits”,例如“15”。 combobox中的15个文本应粘贴在单元格“M8”中,然后是所有后续行“M9”,“M10”等。ComboBox使用的范围是硬编码的,所有选项都是所有string(没有数字)。

在下面的代码.SelectedItem错误发生。 当我使用它作为文本框(不包括select代码的combobox部分)时,循环工作。

请让我知道,如果我可以在这里提供更多的信息来协助您的答案。

谢谢,

尼尔

Sub Incomes_Patch() Dim Counter As Integer Dim ws As UserForm Dim Total As Integer Dim Incomes As String Set ws = UserForm(this.CboIncomesPatch.GetItemText(Me.CboIncomesPatch.SelectedItem)) Set Incomes.Value = ws Total = TxtNumberOfUnits.Value Counter = 0 Application.ActiveSheet.range("M8").Select Do While Counter <= Total If Counter = Total Then Exit Do ActiveCell.Value = Incomes + Counter ActiveCell.Offset(1, 0).Select Counter = Counter + 1 Loop End Sub 

请在下面find正确的代码来做到这一点:

 Sub Incomes_Patch() Dim Counter As Integer 'Dim ws As UserForm Dim Total As Integer Dim Incomes As String 'I am not sure why you wanted the form object, you need the combobox value right? you can directly get it from Combobox. 'Set ws = UserForm(this.CboIncomesPatch.GetItemText(Me.CboIncomesPatch.SelectedItem)) Incomes = Me.CboIncomesPatch.Text ' selected item doesn't work in Combo, so you need to use Text Total = TxtNumberOfUnits.Text Counter = 0 Application.ActiveSheet.Range("M8").Select Do While Counter <= Total If Counter = Total Then Exit Do ActiveCell.Value = Incomes & Counter ActiveCell.Offset(1, 0).Select Counter = Counter + 1 Loop End Sub 

它有帮助吗?

谢谢,V

你不能使用combobox的.SelectedText属性吗?

 Set ws = UserForm(Me.CboIncomesPatch.SelectedText) Set Incomes.Value = ws