使用字符串数组的 VBA 中出现“下标超出范围”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16324883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Subscript out of range" error in VBA using array of strings
提问by cacklen
I learned C# and VB.Net in school, but not VBA.
我在学校学过 C# 和 VB.Net,但没有学过 VBA。
I am trying to automate a pipe-delimited .csv export in Access. The user selects a ship date from a combobox and clicks "export", and the application needs to do the rest. The problem is, it is exporting the dates in short date format (m/d/yyyy) no matter how I have them formatted in Access; the client's required format is mmddyyyy.
我正在尝试在 Access 中自动执行以管道分隔的 .csv 导出。用户从组合框中选择发货日期并单击“导出”,应用程序需要完成剩下的工作。问题是,无论我如何在 Access 中格式化日期,它都会以短日期格式 (m/d/yyyy) 导出日期;客户端要求的格式为 mmddyyyy。
I tried appending the date to a text field in another table but Access won't let me do that. So I placed a textbox on the form and typed the date in the correct format and used that to populate the table to be exported, and that works.
我尝试将日期附加到另一个表中的文本字段,但 Access 不允许我这样做。所以我在表单上放置了一个文本框,并以正确的格式输入日期,然后用它来填充要导出的表格,这很有效。
What I am trying to do now is write a subroutine to populate the textbox in the correct format whenever the user changes the combobox. I keep getting "Runtime Error 9: Subscript out of range" on the following line: If Len(dateParts(0)) = 2 Then
我现在要做的是编写一个子程序,以便在用户更改组合框时以正确的格式填充文本框。我在以下行中不断收到“运行时错误 9:下标超出范围”:If Len(dateParts(0)) = 2 Then
Here is the code I have so far:
这是我到目前为止的代码:
Private Sub tbxShipDate_Change()
Dim strShipDate As String
Dim strTextDate As String
Dim dateParts() As String
strShipDate = Me.tbxShipDate.Value
If Len(strShipDate) = 10 Then
strTextDate = strShipDate
strTextDate = Replace(strTextDate, "/", "")
Else
dateParts = Split(strShipDate, "/")
'check month format
If Len(dateParts(0)) = 2 Then
strTextDate = dateParts(0)
Else
strTextDate = "0" & dateParts(0)
End If
'check day format
If Len(dateParts(1)) = 2 Then
strTextDate = strTextDate & dateParts(1)
Else
strTextDate = strTextDate & "0" & dateParts(1)
End If
'add year
strTextDate = strTextDate & dateParts(2)
End If
Me.tbxTextDate.Value = strTextDate
End Sub
回答by Chris
I think you will need to ReDim your array to the correct length before using it, like this:
我认为您需要在使用之前将数组重新调整为正确的长度,如下所示:
ReDim dateParts(3)
before you can use it.
在你可以使用它之前。