Excel VB脚本error handling – “对象variables或未设置块”错误

我在使用Excel的macros时遇到了一些麻烦。 这给我麻烦的片段负责:

1)允许用户逐个select多个列标题2)按照标题select的顺序取每列的内容,并连接

代码如下:

Dim concat1() As Range Dim rng As Variant Dim i As Variant Dim g As Integer Dim metalabels() As String Dim concated As String Dim s As Variant lastrow = Cells(rows.Count, "A").End(xlUp).Row i = 0 msgselect = MsgBox("Would you like to concatonate?", vbOKCancel) On Error GoTo Errhandler If msgselect = vbOK Then Do ReDim Preserve concat1(i) Set concat1(i) = Application.InputBox("Select the headers you would like to concatonate", Default:=ActiveCell.Address, Type:=8) msgselect = MsgBox("Another cell?", vbOKCancel) i = i + 1 Loop While msgselect = vbOK i = i - 1 Errhandler: End If ReDim metalabels(i) For g = 0 To i metalabels(g) = concat1(g).Text Next ActiveSheet.Range("a1").End(xlToRight).Offset(0, 1).Select ActiveCell = "Situation" For h = 1 To lastrow - 1 For g = 0 To UBound(metalabels) concated = concated + metalabels(g) + ": " + concat1(g).Offset(h, 0).Text + " / " Next ActiveCell.Offset(h, 0).Value = concated concated = "" Next End Sub 

问题在这里:

 Set concat1(i) = Application.InputBox("Select the headers you would like to concatonate", Default:=ActiveCell.Address, Type:=8) 

如果用户select“取消”,则代码崩溃,因为循环取决于vbOK。 所以,我想我会把一个error handling程序,但事实上,我得到的“对象variables或块未设置”错误。

正如你可能感觉到的,我仍然是一个VB的nube。 任何帮助是极大的赞赏。

谢谢!

你有没有尝试joinif concat1(i) = false then exit sub在增加i之前if concat1(i) = false then exit sub

把这个放在你的END IF之后

 If concat1(i) Is Nothing Then Exit Sub