按钮添加列?

时间:2016-12-14 14:02:18

标签: excel vba excel-vba

在excel 2013中,我希望是否有人可以在单击此按钮(即activex控件)后,根据用户输入创建一个代码,用于向电子表格添加1个空白列。该列将根据我的表中有多少行结束,这意味着如果有10行,我不应该在电子表格的第11行看到一列。

我输入要添加的列后,我一直收到错误说应用程序定义或对象错误,我甚至尝试将两个大写字母小写并出现相同的错误。

Private Sub CommandButton2_Click()

Dim x As String
x = InputBox("Enter a column that you want to add: ", "What column?")
If x = "" Then Exit Sub

ColumnNum = x
Columns(ColumnNum & ":" & ColumnNum).Insert shift:=xlShiftRight
Columns(ColumnNum - 1 & ":" & ColumnNum - 1).Copy Range("A1" & ColumnNum)
Columns(ColumnNum & ":" & ColumnNum).ClearContents

End Sub

1 个答案:

答案 0 :(得分:1)

这将帮助您入门:

    Dim x As Variant
    Dim ColumnNum%
    x = InputBox("Enter a column that you want to add: ", "What column?")
    If x = "" Then Exit Sub
    ColumnNum = x
    ThisWorkbook.Sheets("Sheet1").Columns(ColumnNum).Insert shift:=xlRight

    ThisWorkbook.Sheets("Sheet1").Columns(ColumnNum - 1).Copy

    'THe line above doesnt make any sense whatsoever. 
     'Im not going to try and trouble shoot it but it seems like you dont understand how to
     ' properly scuplt things. Youll notice i changed how you strucutred the .copy part. 
     'THe part that doesnt make sense to me is the Range section. 

    ThisWorkbook.Sheets("Sheet1").Columns(ColumnNum).ClearContents

您的代码存在一些问题。

  1. 您需要将Option Explicit放在代码的顶部。你没有声明你的变量。
  2. 您的输入框需要声明为变体
  3. 当我玩这个时,很清楚你并没有完全引用需要插入哪些列的列。注意我的“ThisWorkbook .....”
  4. 您的if语句结构也不正确。
  5. 我建议您花一些时间阅读基础知识:)