我在VBA中编写了一个命令按钮的代码,该代码使用(列)范围作为输入,并具有(列)范围作为输出。我想对引用其他列的其他命令按钮使用相同的代码。我不想重复整个代码,因为只有对列的引用会发生变化。
我无法弄清楚如何将此代码定义为我可以“调用”的函数或子代码。在其他命令按钮的代码中执行列B,C,D等的代码
这是代码。它删除重复项并添加字符串"重命名"到列表的每个元素:
Private sub rename_column_A_Click()
'copy values of sheet1 column A to active sheet
Range("A1:A30").Value = Worksheets("sheet1").Range("A1:A30").Value
'remove duplicates, keeping first value as column header
Columns("A:A").Select
ActiveSheet.Range("$A$2:$A$30").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A" & 2).Select
'add string to each element of list
For i = 2 To 30
If Not Range("A" & i).Value = "" Then
Range("A" & i).Value = "rename " & Range("A" & i).Value
End If
Next i
End Sub
答案 0 :(得分:0)
就像John Coleman建议的那样,你可以让Sub获取一个Range参数:
Private Sub rename_column_A_Click()
ProcessRange "A"
End Sub
Private Sub rename_column_B_Click()
ProcessRange "B"
End Sub
Sub ProcessRange(ColAddress As String)
'copy values of sheet1 column A to active sheet
Range(ColAddress & "1:" & ColAddress & "30").Value = Worksheets("sheet1").Range(ColAddress & "1:" & ColAddress & "30").Value
'remove duplicates, keeping first value as column header
ActiveSheet.Range("$" & ColAddress & ":$" & ColAddress & "$30").RemoveDuplicates Columns:=Array(1), Header:=xlNo
'add string to each element of list
For i = 2 To 30
If Not Range(ColAddress & i).Value = "" Then
Range(ColAddress & i).Value = "rename " & Range(ColAddress & i).Value
End If
Next i
End Sub
我删除了两行Select
代码。我觉得你不需要它们。