Sorcerer13
Programmer
- May 14, 2012
- 4
I want to populate portions of a Word 2010 document by copying in data from an Excel 2010 spreadsheet.
I can happily open the spreadsheet within the VBA in Word, and I can copy in the data, but what I now want to do is to only copy in the data if it exists as a specifically named range in the Excel spreadsheet.
I'm using the following code,which runs to completion, but never identifies the presence of the named range. Can anyone help?
Function SeeIfNamedRangeExists(strname As String, _
strWBName As String) As Boolean
Dim lngPtr As Long
Dim rngTest As Range
Dim strThisSheetName As String
With xlApplication.Workbooks(strWBName)
On Error Resume Next
'*
'** Loop through all sheets in workbook.
'*
For lngPtr = 1 To .Sheets.Count Step 1
strThisSheetName = .Sheets(lngPtr).Name
'*
'** Try to access the named range.
'*
Set rngTest = .Sheets(lngPtr).Range(strname)
'*
'** If there is no error then the name exists.
'*
If Err.Number = 0 Then
'*
'** Set the function to TRUE & exit
'*
NamedRangeExists = True
Exit Function
Else
Err.Clear
End If
Next lngPtr
End With
End Function
Steve
There's nothing quite so rare as common sense!
I can happily open the spreadsheet within the VBA in Word, and I can copy in the data, but what I now want to do is to only copy in the data if it exists as a specifically named range in the Excel spreadsheet.
I'm using the following code,which runs to completion, but never identifies the presence of the named range. Can anyone help?
Function SeeIfNamedRangeExists(strname As String, _
strWBName As String) As Boolean
Dim lngPtr As Long
Dim rngTest As Range
Dim strThisSheetName As String
With xlApplication.Workbooks(strWBName)
On Error Resume Next
'*
'** Loop through all sheets in workbook.
'*
For lngPtr = 1 To .Sheets.Count Step 1
strThisSheetName = .Sheets(lngPtr).Name
'*
'** Try to access the named range.
'*
Set rngTest = .Sheets(lngPtr).Range(strname)
'*
'** If there is no error then the name exists.
'*
If Err.Number = 0 Then
'*
'** Set the function to TRUE & exit
'*
NamedRangeExists = True
Exit Function
Else
Err.Clear
End If
Next lngPtr
End With
End Function
Steve
There's nothing quite so rare as common sense!