问:当Option Explicit
打开时,我如何查看excel中是否存在变量?
我在文本文件中搜索模式,当它找到它时,它会检索该模式的位置(从左边开始的字符长度)。每次找到模式时都会发生这种情况。当它找不到这种模式时,它应该分配一个变量(例如:80)。
我在网上找到的解决方案(IsEmpty, TypeName
)都需要Option Explicit
关闭,我真的希望它能够继续使用。我正在考虑声明匹配并给它们一个默认值0,然后检查值是否为> 0或不。这个问题是我不知道可能有多少场比赛,因此我不知道应该定义多少场比赛。
这是文本文件的样子:
2012 2011
title 1 123,342 123,435
title 2 234,431 645,234
title 3 324,234 -
脚本读取每一行并将数据提取到列中(基于年份)。它通过查找模式(" [0-9]"
)然后查找模式何时发生来实现此目的。这一切都很有效,但是当没有找到模式时(例如在"标题3 - 2011和#34;)脚本停止。 (注意:" - "也可能是一个空格,或者" - ",或几乎任何东西)。
以下是我现在的代码的摘录:
**Top of document**
Dim re As Object, matches As Object, match As Object, submatch
Dim iNoColumns As Integer, ii As Integer, NumberMatch As Variant
Dim sLine As String
**
ReDim iColumns(1 To iNoColumns) As Integer
Set re = CreateObject("vbscript.regexp")
re.Pattern = " [0-9]"
re.IgnoreCase = True
re.Global = True
Set matches = re.Execute(sLine)
For Each match In matches
NumberMatch = match
Next
If VBA.InStr(1, sLine, NumberMatch) > 0 Then
iColumns(1) = VBA.InStr(1, sLine, matches(0).Value)
For ii = 2 To iNoColumns
If matches(ii - 1).Value Is Nothing Then
iColumns(ii) = 70 + (ii * 10)
Else
iColumns(ii) = VBA.InStr(iColumns(ii - 1) + 1, sLine, matches(ii - 1).Value)
Debug.Print "Column " & ii & " starts at: " & iColumns(ii)
End If
Next ii
End If
主要是If matches(ii - 1).Value Is Nothing Then iColumns(ii) = 70 + (ii * 10) Else
部分。这是不起作用的部分,我不知道如何解决它。除非匹配(1)或匹配(2)或匹配(3)(等等)不存在,否则代码的其余工作效果很好。
如果我必须定义或解释上面使用的任何变量,请告诉我。
sLine
是当前行(在包含Scripting.FileSystemObject
的文本文件中阅读)iNoColumns
是列数(这决定了需要多少匹配:如果有2列,则脚本会查找两个匹配项(匹配(0)和匹配项(1))。iColumns(ii)
是每列的长度;根据匹配的位置确定。我尝试了this stackoverflow解决方案(及其所有组合),也尝试了IsNull
。
TypeName
以字符串形式返回matches(ii - 1).Value
。
答案 0 :(得分:0)
For Each match In matches
NumberMatch = match
Next
首先,这实际上是在做你想做的事吗?您是否只想设置matches
中的最后一个对象(无论之前的对象是什么)?
其次,请执行以下操作:
dim matches As Variant
If matches(ii - 1) = "" Then
这应解决此问题(您可能需要包含一个或语句来检查它是否等于0)。
答案 1 :(得分:0)
VBA (source):
| Type | Test | Test2
| Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then |
| Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then
| Object | Is obj.Property Is Nothing Then |
| String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then
| Variant | If obj.Property = Empty Then |
或enderlands解决方案(这篇文章)。
Javascript (source):
if(typeof variable_here === 'undefined'){
// your code here.
};
或
if(! variable_here){
// your code here.
};
Phython (source):
try:
thevariable
except NameError:
print "well, it WASN'T defined after all!"
else:
print "sure, it was defined."
或(source) 检查局部变量是否存在:
if 'myVar' in locals():
# myVar exists.
检查是否存在全局变量:
if 'myVar' in globals():
# myVar exists.
检查对象是否具有属性:
if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
其他:Easy way to check that a variable is defined in python?和How do I check if a variable exists?。