VBA“Compile Error:Statement invalid outside Type Block”for variable

我想在一个函数( CommandButton2_Click )中使用全局variables( cmb )将列从一个工作簿复制到另一个使用VBA。 这是我的代码:

 Dim wb As Workbook Dim cmb As String Private Sub ComboBox1_Change() Cell As Range, rng As Range, sht As Worksheet Set 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() 'Copy Column from one workbook to another 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 

Private Sub ComboBox1_Change()出现Compile Error: Statement invalid outside Type Block错误的Compile Error: Statement invalid outside Type Block 。 我想知道为什么。 我已经将variablescmb声明为全局variables。 为什么这个variables不在范围之内?

我相信它必须是:

 Public wb as Workbook Public cmb as String 

和:

 Private Sub ComboBox1_Change() Dim Cell As Range, rng As Range, sht As Worksheet