我有很多子程序在我的宏中几乎完全相同,所以我试图将它压缩成一个我可以多次调用的泛型子程序。这就是我到目前为止所拥有的:
Sub Compare(wksheet As String, table As String, col1 As String, col2 As String, target As String)
Worksheets(wksheet).Activate
Range("table[[#Headers],[target]]").Select
On Error Resume Next
Dim tg_row As Integer
tg_row = 1
For Each tg_cl In Range("table[target]")
If Range("table[col1]").Cells(tg_row, 1).Value = Range("table[col2]").Cells(tg_row, 1).Value Then
tg_cl.Value = "Yes"
Else
tg_cl.Value = "No"
End If
tg_row = tg_row + 1
Next tg_cl
End Sub
这应该可以比较两列并写'#34;是"或"否"如果它们在第三列中相同或不相同。问题是当我尝试运行调用它的子时,例如:
Sub Compare_Data()
Call Compare("Comparison Sheet", DataTbl, Data1Header, Data2Header, DataSameHeader)
End Sub
我得到了#34; ByRef参数类型不匹配"错误。我究竟做错了什么?我应该在表格和标题名称周围加上引号吗?如何在不破坏原始子的情况下做到这一点?提前谢谢。
答案 0 :(得分:0)
这可能会有所帮助(根据要求修改):
Sub Compare(wksheet As WorkSheet, table As Object, col1 As Range, _
col2 As Range, target As Range)
'or you can use As Variant if you want to retain your piece of code
''''
''''
End Sub
和
Sub Compare_Data()
Dim wks As WorkSheet
Dim table1 As Object
Dim Data1Header As Range
Dim Data2Header As Range
Dim DataSameHeader As Range
Set wks = Thisworkbook.Sheets("Comparison Sheet")
Set table1 = ActiveSheet.ListObjects(1)
Set Data1Header = Range(table1).Cells(0, 1)
Set Data2Header = Range(table1).Cells(0, 2)
'Set DataSameHeader = '''''''''
Call Compare(wks, table1, Data1Header, Data2Header, DataSameHeader)
''''
''''
''''
Set table1 = Nothing
Set Data1Header = Nothing
Set Data2Header = Nothing
End Sub
答案 1 :(得分:0)
好的,所以我不完全理解我是如何工作的,但确实如此,我将与大家分享我的成果。这是我的代码现在的样子:
'This is the generalized subroutine that all comparison subroutines will reference when running
Sub Compare(wksheet As String, table As String, col1 As String, col2 As String, target As String)
'This activates the worksheet with the appropriate table and selects the top of the table
Worksheets(wksheet).Activate
Range(table & "[[#Headers]," & target & "]").Select
On Error Resume Next
'The valid range of an Integer variable is -2147483648 through +2147483647
Dim tg_row As Integer
tg_row = 1
'This will compare the two columns and will mark "Yes" or "No" if they match or not in the third column
For Each tg_cl In Range(table & target)
If Range(table & col1).Cells(tg_row, 1).Value = Range(table & col2).Cells(tg_row, 1).Value Then
tg_cl.Value = "Yes"
Else
tg_cl.Value = "No"
End If
tg_row = tg_row + 1
Next tg_cl
End Sub
所以我重新设置了这个像这样设置的子:
Sub Compare_Data()
Call Compare("Comparison Sheet", "DataTbl", "[Data1Name]", "[Data2Name]", "[DataSameName]")
End Sub
它有效!希望这是有帮助的,也是有道理的,因为我还在试图弄清楚它是如何成功的。