方法' Union'对象' _Global'失败

时间:2017-05-24 17:10:34

标签: excel vba ms-access

我在第二次导出excel电子表格时不断收到此错误。

我看到的反复出现的答案是联盟中使用的rng需要设置为空。我在我的代码中一遍又一遍地做到这一点无济于事,还有什么我可能会遗漏。

非常感谢对此的任何见解。

Set myRange = ApXL.Sheets(xlWSh.Name).Range("1:1")
Set LastCell = myRange.Cells(myRange.Cells.count)
Set FoundCell = myRange.Find(what:=fnd, After:=LastCell)

If Not FoundCell Is Nothing Then
  FirstFound = FoundCell.Address
Else
  GoTo NoValuesMatchingFound
End If
Set rng = FoundCell

'Loop until cycled through all unique finds
Do Until FoundCell Is Nothing
  'Find next cell with fnd value
  Set FoundCell = myRange.FindNext(After:=FoundCell)
  'Add found cell to rng range variable
  Set rng = Union(rng, FoundCell)
  'Select Cells Containing Find Value
  'Test to see if cycled through to first found cell
  If FoundCell.Address = FirstFound Then Exit Do
Loop

 rng.EntireColumn.Select
 ApXL.Selection.NumberFormat = "dd-mm-yy  hh:mm:ss"

'Error Handler
NoValuesMatchingFound:
' Debug.Print "No values were found in this worksheet"

' selects all of the cells
 ApXL.ActiveSheet.Cells.Select
 ' does the "autofit" for all columns
 ApXL.ActiveSheet.Cells.EntireColumn.AutoFit
 ' selects the first cell to unselect all cells
 xlWSh.Range("A1").Select

 On Error Resume Next
 xlWBk.Sheets("Sheet2").Delete
 xlWBk.Sheets("Sheet3").Delete
 On Error GoTo 0

 With xlWBk
   If cmbOverwrite <> "Prompt" Then
     ApXL.DisplayAlerts = False 
   Else
     ApXL.DisplayAlerts = True
   End If
   .SaveAs FileName:=txtSaveToFolder & "\" & File_Name & ".xlsx"
   Set rng = Nothing
   .Close
 End With
 rstXX.Close

1 个答案:

答案 0 :(得分:1)

更改

Set rng = Union(rng, FoundCell)

Set rng = ApXL.Union(rng, FoundCell)

因为您正在尝试使用Union命令,该命令是Excel Application对象的一部分。