有没有办法让我在Excel宏(或加载项)中获取逻辑来从多个电子表格中提取和操作数据?
以下内容:对于电子表格A中的每一行(如果电子表格中的网站网址A =电子表格B中的网站网址,则将值“电子表格B列X”复制到电子表格A列Y中。)
答案 0 :(得分:0)
sheets()
命令在工作表之间切换完成的。您可以使用索引(它们从1开始),或者如果您有命名工作表,则可以键入名称作为字符串sheets("reports").activate
此代码将为您进行比较。我们假设工作表A
为Sheets(1)
,工作表B
为sheets(2)
,我们仅比较两个工作表中的A
列
Sub test()
col_2_search = "A"
LastRowA = Sheets(1).Cells(Sheets(1).Rows.Count, col_2_search ).End(xlUp).Row
For curr_row = 1 To LastRowA
val_from_a = Sheets(1).Cells(curr_row, col_2_search ).Value
val_from_b = Sheets(2).Cells(curr_row, col_2_search ).Value
If (val_from_a = val_from_b) Then
'this should be where you put your copy paste code
MsgBox ("match row " & curr_row & " value:" & val_from_a)
End If
Next
End Sub
修改强>
使用匹配的替代解决方案。可能有一种更清晰的方式来写这个,但我只是很快就把它扔了
Sub test()
col_2_search = "A"
LastRowA = Sheets(1).Cells(Sheets(1).Rows.Count, "A").End(xlUp).Row
LastRowB = Sheets(2).Cells(Sheets(2).Rows.Count, "A").End(xlUp).Row
For curr_row = 1 To LastRowA
value_from_A = Sheets(1).Cells(curr_row, col_2_search ).Value
'we are searching B from column 1 to the last populated column in b
Var = Application.Match(value_from_A, Range(Sheets(2).Cells(1, col_2_search ), Sheets(2).Cells(LastRowB, col_2_search )))
'if there wasn't an error, var contains the row of range B that matches
'a
If Not (IsError(Var)) Then
MsgBox ("Row " & curr_row & " of A matches row " & Var & " of B, both contain: " & value_from_A)
End If
Next
End Sub