大家好,提前谢谢。
我目前在工作簿中有一个VBA来复制" Demand Log"改变日志"改变日志"列中的单元格" O"有特定的价值。
VBA工作得很好,但我现在希望将两个工作表分开并为每个工作簿分别设置一个工作簿。
我的问题是 - 如何更改我的VBA以便在工作簿之间复制和粘贴,而不是在工作表之间复制和粘贴?
请参阅下面的我的VBA代码:
Dim xRg As Range
Dim xCell As Range
Dim I As Long
Dim J As Long
Dim K As Long
I = Worksheets("Demand Log").UsedRange.Rows.Count
J = Worksheets("Change Log").Cells(Worksheets("Change Log").Rows.Count, "B").End(xlUp).Row
If J = 1 Then
If Application.WorksheetFunction.CountA(Worksheets("Change Log").Range) = 0 Then J = 0
End If
Set xRg = Worksheets("Demand Log").Range("O5:O" & I)
Application.ScreenUpdating = False
For K = xRg.Count To 1 Step -1
If CStr(xRg(K).Value) = "Change Team" Then
J = J + 1
With Worksheets("Demand Log")
Intersect(.Rows(xRg(K).Row), .Range("A:Z")).Copy Destination:=Worksheets("Change Log").Range("A" & J)
Intersect(.Rows(xRg(K).Row), .Range("A:Z")).Delete xlShiftUp
End With
End If
Next
Application.ScreenUpdating = True
答案 0 :(得分:1)
您应该同时参考您的工作表和工作簿。所以,而不是:
I = Worksheets("Demand Log").UsedRange.Rows.Count
您应该输入:
I = Workbooks("Book1").Worksheets("Demand Log").UsedRange.Rows.Count
代码中的任何位置。为简单起见,您可以设置对象变量,例如:
Dim wb1 as Workbook
Set wb1 = Application.Workbooks("Book1")
或者,更好的是,将工作表设置为变量,例如:
Dim wsDemand as Worksheet
Set wsDemand = Workbooks("Book1").Worksheets("Demand Log")
然后您可以在代码中的任何位置使用wsDemand而不是Worksheets(" Demand Log")。 Book1当然是默认工作簿的名称,您的文件可能还有其他名称。
答案 1 :(得分:0)
如果工作簿已打开,那么您可以像这样引用它:
Workbooks("mybook.xls")[.method]
如果工作簿已关闭,您需要将其打开:Workbooks.Open("C:\path\mybook.xls")[.method]
您可以将它们分配给变量:
set wb = Workbooks("mybook.xls")
set wb = Workbooks.Open("C:\path\mybook.xls")
set ws = wb.Sheets("MySheet")
您还可以访问工作表并将其分配给变量:(如果您使用的是单页,则非常有用)
set ws = Workbooks("mybook.xls").Sheets("MySheet")
set ws = Workbooks.Open("C:\path\mybook.xls").Sheets("MySheet")
未经测试,但试一试:
Sub mysub()
Dim xRg As Range
Dim xCell As Range
Dim I As Long
Dim J As Long
Dim K As Long
Dim wbDem As Workbook
Dim wbChg As Workbook
Dim wsDem As Worksheet
Dim wsChg As Worksheet
'Open/Get Workbook
If Application.Workbooks("Demand.xls") Is Nothing Then
Set wbDem = Application.Workbooks.Open("C:\path\Demand.xls")
Else
Set wbDem = Application.Workbooks("Demand.xls")
End If
'Open/Get Workbook
If Application.Workbooks("Change") Is Nothing Then
Set wbChg = Application.Workbooks.Open("C:\path\Change.xls")
Else
Set wbChg = Application.Workbooks("Change.xls")
End If
'Set Sheet Variables
Set wsDem = wbDem.Worksheets("Demand Log")
Set wsChg = wbChg.Worksheets("Change Log")
I = wsDem.UsedRange.Rows.Count
J = wsChg.Cells(wbChg.Rows.Count, "B").End(xlUp).Row
If J = 1 Then
If Application.WorksheetFunction.CountA(wbChg.Range) = 0 Then J = 0
End If
Set xRg = wsDem.Range("O5:O" & I)
Application.ScreenUpdating = False
For K = xRg.Count To 1 Step -1
If CStr(xRg(K).value) = "Change Team" Then
J = J + 1
With wsDem
Intersect(.Rows(xRg(K).Row), .Range("A:Z")).Copy Destination:=wsChg.Range("A" & J)
Intersect(.Rows(xRg(K).Row), .Range("A:Z")).Delete xlShiftUp
End With
End If
Next
Application.ScreenUpdating = True
End Sub