gpt4 book ai didi

vba - 有条件地将 Excel File-2 数据复制到 Excel File-1?

转载 作者:行者123 更新时间:2023-12-04 21:57:42 25 4
gpt4 key购买 nike

我正在使用 Excel 2007。当文件 1 与文件 2 中的某些列数据匹配时,我尝试将单价从 Excel 文件 2 数据复制到 Excel 文件 1。

感谢您的帮助和指导。

我的 VBA 代码:

子 mySales()
将 LastRow 作为整数,i 作为整数,erow 作为整数,Pipe_Class 作为字符串,Pipe_Description 作为字符串,End_Type 作为字符串,Pipe_Size 作为字符串
将 wbk 调暗为工作簿
strPriceFile = "C:\Temp\File-2.xlsx"
LastRow = ActiveSheet.Range(“A” & Rows.Count).End(xlUp).Row
对于 i = 2 到 LastRow
Pipe_Class = ""
Pipe_Description = ""
End_Type = ""
Pipe_Size = ""
Pipe_Class = ActiveSheet.Cells(i, 1).Value
Pipe_Description = ActiveSheet.Cells(i, 2).Value
End_Type = ActiveSheet.Cells(i, 3).Value
Pipe_Size = ActiveSheet.Cells(i, 4).Value
设置 wbk = Workbooks.Open(strPriceFile)
工作表(“SOR2”)。选择
如果 Cells(i, 1) = Pipe_Class And Cells(i, 2) = Pipe_Description And Cells(i, 3) = End_Type And Cells(i, 4) = Pipe_Size Then
范围(单元格(i,12),单元格(i,12))。选择
选择.复制

???在这里之后如何选择我当前的文件并粘贴??????????

工作表(“SOR1”)。选择
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 12).Select
ActiveSheet.Paste
ActiveWorkbook.Save
万一
接下来我
ActiveWorkbook.关闭
Application.CutCopyMode = False
结束子

最佳答案

我没有检查您的所有代码,但我已经重构了您在问题中的内容,以尝试打开工作簿一次并分配适当的对象,以便您可以跟踪对哪个工作表应用了哪些操作。

Sub mySales() 
Dim LastRow As Integer, i As Integer, erow As Integer
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim wbDst As Workbook
Dim wsDst As Worksheet
Dim strPriceFile As String

Set wbDst = ActiveWorkbook
Set wsDst = ActiveSheet

strPriceFile = "C:\Temp\File-2.xlsx"
Set wbSrc = Workbooks.Open(strPriceFile)
Set wsSrc = wbSrc.Worksheets("SOR2")

LastRow = wsDst.Range("A" & wsDst.Rows.Count).End(xlUp).Row
erow = LastRow + 1

For i = 2 To LastRow
If wsSrc.Cells(i, 1).Value = wsDst.Cells(i, 1).Value And _
wsSrc.Cells(i, 2).Value = wsDst.Cells(i, 2).Value And _
wsSrc.Cells(i, 3).Value = wsDst.Cells(i, 3).Value And _
wsSrc.Cells(i, 4).Value = wsDst.Cells(i, 4).Value Then

wsSrc.Cells(i, 12).Copy wsDst.Cells(erow, 12)
erow = erow + 1 ' your current code would always copies to the same row,
' but I **think** you probably want to copy to the
' next row each time
End If
Next i

wbSrc.Close
If erow > LastRow + 1 Then
wbDst.Save
End If
wbDst.Close
End Sub

该代码完全未经测试,但即使它不起作用,至少它应该让您了解应该如何处理多个工作簿和多个工作表。

关于vba - 有条件地将 Excel File-2 数据复制到 Excel File-1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41274871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com