VBA代码有时会返回错误,有时则不会

时间:2017-08-16 05:26:41

标签: excel vba

我已经编写了下面的代码,但我似乎无法发现它有什么问题。该程序设置为从工作簿传输数据:

  

SRJem.xlsx

到写下面代码的活动工作簿。现在,我同时打开了两个工作簿(我不想在执行操作时关闭它们)。问题是,代码在某些时候是成功的,而在某些时候它会在第15行返回错误。我尝试在操作前保存它们但仍然会发生。

第15行:

  

ws.Cells(iRow,4).Value = wbSource.Sheets(" 1")。Cells(14,1).Value

我需要一些关于我所犯错误的轻松解释。非常感谢你。

Sub transfer_to_masterfile()

'find first empty row in database
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("1")
Dim wbSource As Workbook

iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).row + 1

Set wbSource = Workbooks.Open("C:\Users\fed.staff01\Desktop\J.G.E - QS\6. EXCEL PROGRAMS\SRJem.xlsx") ' <<< path to source workbook

'Now, transfer values from wbSource to wbTarget:
ws.Cells(iRow, 4).Value = wbSource.Sheets("1").Cells(14, 1).Value
ws.Cells(iRow, 5).Value = wbSource.Sheets("1").Cells(6, 4).Value

Dim mats As String
Dim row As Integer

row = 23

Do
    mats = mats & "  " & wbSource.Sheets("1").Cells(row, 1).Value & "  " & wbSource.Sheets("1").Cells(row, 3).Value & _
    "             " & wbSource.Sheets("1").Cells(row, 5).Value

    If wbSource.Sheets("1").Cells(row + 1, 1).Value > 0 Then
        mats = mats & vbNewLine
    End If

    If wbSource.Sheets("1").Cells(row + 1, 1).Value = "" Then
        Exit Do
    End If

    row = row + 1

Loop Until row = 42

ws.Cells(iRow, 7).Value = mats
'ws.Cells(iRow, 5).Value = wbSource.Sheets("1").Cells(6, 4).Value

'wbSource.Close
'wbTarget.Close

End Sub

1 个答案:

答案 0 :(得分:0)

在您提到的那一行,有许多条件可以避免错误:

1) there must be a file with the name specified for `wbSource`
2) that file must open with an activeSheet named `1`
3) the program workbook (`ws`) must also have a worksheet named `1`
4) there must be a `*` on the activeSheet of the `ws` workbook

请注意,有两种情况取决于activeSheet。为避免这种情况,我建议为您引用的每个工作表(例如set sh = ws.worksheets("1"))创建一个变量,以便您不依赖于该工作表是否处于活动状态。根据我的经验,这通常是问题,但上面提到的其他条件也可能是问题。