我为很多系统开发了一个vba。我在这里举两个系统的例子:
Private Sub Macro1()
Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\System1.xls")
With x.Sheets("System1")
Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues,
LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False)
.Range(aCell1,
.Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_
ThisWorkbook.Sheets("System1").Range("A2")
End With
Private Sub Macro2()
Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\System2.xls")
With x.Sheets("System2")
Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues,
LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False)
.Range(aCell1,
.Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_
ThisWorkbook.Sheets("System1").Range("A2")
End With
有没有办法可以在数组或列表中提及所有系统名称,而不是为不同的系统编写不同的子系统? 因为唯一要改变的是系统编号
答案 0 :(得分:3)
您只需要重构代码:
Private Sub Macro1()
GetData 1
End Sub
Private Sub Macro2()
GetData 2
End Sub
Sub GetData(systemNum as long)
Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\System" & systemNum & ".xls")
With x.Sheets("System" & systemNum)
Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues,
LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False)
.Range(aCell1,
.Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_
ThisWorkbook.Sheets("System1").Range("A2")
End With
End Sub
答案 1 :(得分:2)
尝试将系统添加为参数。在下面的示例中,它是可选的:
Option Explicit
Private Sub Macro1(Optional strParam As String = "System1")
Set x = Workbooks.Open("C:\Users\****\Desktop\New folder\" & strParam & ".xls")
With x.Sheets(strParam)
Set aCell1 = .Range("A1:X1000").Find(What:="User", LookIn:=xlValues,
LookAt:=xlWhole, _MatchCase:=False, SearchFormat:=False)
.Range(aCell1,
.Cells(.Rows.Count,aCell1.Column).End(xlUp)).Offset(2,0).Copy_
ThisWorkbook.Sheets(strParam).Range ("A2")
End With
End Sub
这就是你所说的:
Public Sub TestMe()
Macro1 'same as Macro1 "System1"
Macro1 "System1"
Macro1 "System2"
End Sub
编辑:就原始数据而言,这是一个可能的解决方案,您可以使用上面的Macro1子修复:
Public Sub TestMe()
Dim myArr As Variant
Dim lngCounter As Long
myArr = Array("System1", "System2", "System3")
For lngCounter = LBound(myArr) To UBound(myArr)
Macro1 myArr(lngCounter)
Next lngCounter
End Sub