我想比较两个不同 Excel 文件中的单元格值。
我已经完成了一个程序,如果在同一张表上,该程序可以正常工作。现在,我想“外部化”第一个单元格。该程序应该将一列的每一行与另一个电子表格进行比较
Sub Update_production()
Dim i As Integer, j As Integer, refmiss As Integer, comments As String
i = 5
j = 15
refmiss = 0
Do while '[Production pallet.xlsx]September'!$A$i.Value <> ""
Do While Cells(j, 1).Value <> ""
If (Cells(i, 1).Value <> Cells(j, 1).Value) Then
j = j + 1
Else
Cells(j, 3).Value = Cells(j, 3).Value + Cells(i, 3).Value
Cells(j, 4).Value = Cells(j, 4).Value + Cells(i, 4).Value
j = j + 1
refmiss = 1
End If
Loop
If (refmiss = 0) Then
comments = Cells(i, 1).Value
Range("A15").Select
ActiveCell.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = comments
ActiveCell.Offset(0, 2).Value = Cells(i, 3).Value
ActiveCell.Offset(0, 3).Value = Cells(i, 4).Value
End If
refmiss = 0
i = i + 1
j = 15
Loop
End Sub
提前感谢您的帮助(如果可以保留 do while,那就太好了,因为我不知道两个电子表格中会有多少行)
答案1
您需要使用应用程序.工作簿.打开方法。
Sub Openfilemacro()
Dim myfile As String
myfile = "Path\to\file"
Application.Workbooks.Open Filename:=myfile
End Sub
然后,您可以在工作簿之间进行引用进行比较,只需指定 WB 和 WS,就像您已经做的那样。
类似这样的,但为你做了调整 -
Sub Openfilemacro()
Dim myfile As String
Dim workbookA As Workbook
Dim workbookB As Workbook
myfile = "Path\to\file"
workbookA = ThisWorkbook
workbookB = Application.Workbooks.Open(Filename:=myfile)
Dim c As Range
For Each c In Workbooks(workbookA).Range("A:A")
If c = "" Then Exit Sub
'search workbookB for c.value
'do stuff
Next
End Sub
简短说明 - 您可能希望避免使用.select
和activecell
属性,因为它可能会变得混乱。尝试始终引用实际单元格,并且无需选择单元格。也许您需要一个workbook.activate
,但一般来说,不需要选择任何内容或引用活动单元格,尤其是for loop
已经存在。