我想用一个全局变量(cmb
)的函数(CommandButton2_Click
)从一个工作簿复制列到另一个使用VBA。 这是我的代码: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
错误。我想知道为什么。我已将变量cmb
声明为全局变量。为什么变量不在范围内?
您没有设置白平衡'设置白平衡= Workbooks.Open(sFilePath)' – danieltakeshi
您还没有'set'一个字符串变量'设置中巴= ..'应该只是'CMB = ...' –
你缺少关键字'Dim'上'小区范围,RNG量程,SHT作为Worksheet' –