昨天我已经收到了关于此代码的帮助,但我对VBA完全不熟悉所以我遇到了困难。解释我的代码:
我正在尝试将一系列单元格从一个工作簿复制到另一个工作簿中的相同范围的单元格,但工作表的名称必须相同。所以代码应该测试工作表是否存在,然后它会在两个工作簿中找到相应的工作表。如果名称相同,它将采用该值,但如果不是,它将继续浏览工作簿1中的所有工作表以找到正确的工作表。代码贯穿始终,但它并没有复制单元格。
我认为这个问题可能源于第一个循环中的sheetexists行。我被告知我需要确保在运行循环之前检查表单是否存在,但我不确定如何执行此操作。
谢谢!
Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
Sub foo()
Dim wbk1 As Workbook
Dim wbk2 As Workbook
Dim shtName1 As String
Dim shtName2 As String
Dim i As Integer
Dim p As Integer
Set wkb1 = Workbooks.Open("C:\Users\lliao\Documents\Trad Reconciliation.xlsx")
Set wkb2 = Workbooks.Open("C:\Users\lliao\Documents\TradReconciliation.xlsx")
i = 2
p = 2
shtName2 = wkb2.Sheets(i).Name
shtName1 = wkb1.Sheets(p).Name
For i = 2 To wkb2.Worksheets.Count
If (SheetExists(shtName2) = True) And (SheetExists(shtName1) = True) Then
For p = 2 To wkb1.Worksheets.Count
If shtName2 = shtName1 Then
wkb2.Sheets(shtName2).Range("D2:G2").Value = wkb1.Sheets(shtName1).Range("D2:G2").Value
End If
Next p
End If
Next i
End Sub
答案 0 :(得分:0)
您设置shtName2 = wkb2.Sheets(i).Name
,但之后再也不会更改它。所以它总是只看一张纸。
您的foo
子例程应更改为:
Sub foo()
Dim wbk1 As Workbook
Dim wbk2 As Workbook
Dim i As Integer
Set wbk1 = Workbooks.Open("C:\Users\lliao\Documents\Trad Reconciliation.xlsx")
Set wbk2 = Workbooks.Open("C:\Users\lliao\Documents\TradReconciliation.xlsx")
For i = 2 To wbk2.Worksheets.Count
If SheetExists(wbk2.Worksheets(i).Name, wbk1) Then
wbk2.Worksheets(i).Range("D2:G2").Value = wbk1.Worksheets(wbk2.Worksheets(i).Name).Range("D2:G2").Value
End If
Next i
End Sub
将Option Explicit
作为代码模块的第一行包含在内也是一个好主意。我的答案中有拼写错误,因为我复制/粘贴了原始代码,但您已定义变量wbk1
和wbk2
,然后使用wkb1
和wkb2
代替。由于wkb1
和wkb2
未明确声明,因此它们被隐式创建为Variant
,然后导致代码中出现问题Workbook
。
Option Explicit
指示编译器强制您显式声明所有变量,从而拾起这样的拼写错误。