使用VBA将列从一个工作表复制到另一个工作表

我试图从一张纸复制到另一个不同的工作簿。 这是我的复制代码:

Private Sub CommandButton2_Click() Dim sourceColumn As Range, targetColumn As Range Set sourceColumn = wb.Worksheets(cmb).Columns(Form.ComboBox2.Value) Set targetColumn = ActiveWorkbook.ActiveSheet.Columns("PART NUMBER") sourceColumn.Copy Destination:=targetColumn End Sub 

cmb是一个全局variables。 我得到一个Run Time Error 13: Type MismatchSet sourceColumn = wb.Worksheets(cmb).Columns(Form.ComboBox2.Value)

有人可以指出什么是怎么回事,这是如何解决的?

整个代码:

 Public wb As Workbook Public cmb As String Private Sub ComboBox1_Change() Dim Cell As Range, rng As Range, sht As Worksheet cmb = Form.ComboBox1.Value Set sht = wb.Worksheets(cmb) 'assuming your headers are always on the first row... Set rng = sht.Range(sht.Range("A1"), _ sht.Cells(1, Columns.Count).End(xlToLeft)) 'add some code here to clear the lists first!... For Each Cell In rng.Cells If Len(Cell.Value) > 0 Then Form.ComboBox2.AddItem (Cell.Value) Form.ComboBox3.AddItem (Cell.Value) Form.ComboBox4.AddItem (Cell.Value) Form.ComboBox5.AddItem (Cell.Value) Form.ComboBox6.AddItem (Cell.Value) Form.ComboBox7.AddItem (Cell.Value) Form.ComboBox8.AddItem (Cell.Value) Form.ComboBox9.AddItem (Cell.Value) Form.ComboBox10.AddItem (Cell.Value) Form.ComboBox11.AddItem (Cell.Value) Form.ComboBox12.AddItem (Cell.Value) Form.ComboBox13.AddItem (Cell.Value) End If Next Cell End Sub Private Sub CommandButton1_Click() Dim sFilePath As String sFilePath = Application.GetOpenFilename() Set wb = Workbooks.Open(sFilePath) For Each sht In wb.Worksheets Form.ComboBox1.AddItem sht.Name Next sht End Sub Private Sub CommandButton2_Click() Dim sourceColumn As Range, targetColumn As Range Set sourceColumn = wb.Worksheets(cmb).Columns(Form.ComboBox2.Value) Set targetColumn = ActiveWorkbook.ActiveSheet.Columns("PART NUMBER") sourceColumn.Copy Destination:=targetColumn End Sub 

可能您没有在Columns()中将parameter passing给正确的值。 如果您使用macroslogging器,您将看到Columns的参数如下所示:

"E:G"在一个简单的macrosColumns("E:G").Select 。 或者一个数字作为Columns(5).Select 。select。

尝试一个非常简单的修复,将错误的行更改为以下内容:

Set sourceColumn = wb.Worksheets(cmb).Columns("A:D")如果它工作,然后尝试重拍代码。