对于变量,VBA“编译错误:语句在类型块外部无效”

时间:2017-09-28 18:56:09

标签: excel vba excel-vba

我想在函数(cmb)中使用全局变量(CommandButton2_Click),使用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

我在Compile Error: Statement invalid outside Type Block收到Private Sub ComboBox1_Change()错误。我想知道为什么。我已将变量cmb声明为全局变量。为什么变量不在范围内?

1 个答案:

答案 0 :(得分:1)

我认为必须是:

Public wb as Workbook
Public cmb as String

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