我在使用Excel的宏时遇到了一些麻烦。给我带来麻烦的片段负责:
1)允许用户逐个选择多个列标题 2)按标题选择的顺序获取每列的内容,并连接
以下是代码:
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)
如果用户选择“取消”,则代码崩溃,因为循环取决于vbOK。所以,我以为我会放入一个错误处理程序,但实际上,我得到“对象变量或没有设置块”错误。
正如你可能感觉到的那样,我仍然是一个用VB做的人。任何帮助是极大的赞赏。
谢谢!
答案 0 :(得分:1)
在结束IF之后放置
If concat1(i) Is Nothing Then Exit Sub
答案 1 :(得分:0)
在递增i之前,您是否尝试添加if concat1(i) = false then exit sub
?