简体   繁体   English

在生成命名范围的VBA代码中添加错误检查

[英]Adding an error check to VBA code that generates named ranges

I have been using the following code to generate named ranges for datasets with a large number of columns 我一直在使用以下代码为具有大量列的数据集生成命名范围

Sub Make_Named_Ranges()

Range("A1").Select
ActiveSheet.UsedRange

Dim rCell2 As Range
Dim wb2 As Workbook, ws2 As Worksheet

ActiveSheet.UsedRange.Select
Set ws2 = Selection.Parent
Set wb2 = ws2.Parent

For Each rCell2 In Selection.Cells

If rCell2.Address = "$A$2" Then Exit For

wb2.Names.Add rCell2.Value, "=" & ws2.Cells(2, rCell2.Column).Address  
& _":" & ws2.Cells(ActiveSheet.Range("A"&   Rows.Count).End(xlUp).Row,rCell2.Column).Address

Next rCell2
End Sub

What I would like to add is a form of error checking - occassionally the code encounters a column heading in row 1 that isn't a valid name (eg, M2 or SP500). 我想添加的是一种错误检查形式-有时,代码在第1行中遇到的列标题不是有效名称(例如M2或SP500)。 Is there a simple way to have it just skip this column and keep going when it encounters an invalid name? 有没有一种简单的方法让它跳过此列并在遇到无效名称时继续前进?

The simplest way to do this is to change the error handling. 最简单的方法是更改​​错误处理。 Include this code immediately before the line(s) of code that generates the error: 紧接在生成错误的代码行之前包括以下代码:

On Error Resume Next

This code instructs the script to ignore any errors generated from that point on. 此代码指示脚本忽略此后生成的任何错误。 If an error occurs, no error message will be generated and the script will continue to the next line of code. 如果发生错误,则不会生成任何错误消息,并且脚本将继续到下一行代码。

Turn error handling back on for the rest of the script by adding this immediately after the line(s) generating the error: 通过在生成错误的行之后立即添加以下内容,重新打开脚本其余部分的错误处理:

On Error Goto 0

There are better ways of dealing with errors but this is probably the easiest to use. 有更好的处理错误的方法,但这可能是最容易使用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM