Private Declare Function CopyMemory Lib "kernel32" Alias "RtlMoveMemory" () Declare Function CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) As Boolean Dim arr() Private Sub Command1_Click() Sub Command1_Click() ReDim Preserve arr(UBound(arr) + 1) Debug.Print UBound(arr) Dim i As Long, j As Long i = CLng(Text2.Text) 2: If Val(i) > UBound(arr) - 1 Then MsgBox "您輸入的位置數值過大", , "信息提示" GoTo 2 Else CopyMemory arr(i + 1), arr(i), (UBound(arr) - i + 2) * 16 arr(i) = CLng(Text3.Text) Text4.Text = "" For j = LBound(arr) To UBound(arr) If j <> 0 Then Text4.Text = Text4.Text & "," End If Text4.Text = Text4.Text & arr(j) Next j End If End Sub Private Sub Form_Load() Sub Form_Load() Dim j As Long arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) Text1.Text = "" For j = LBound(arr) To UBound(arr) If j <> 0 Then Text1.Text = Text1.Text & "," End If Text1.Text = Text1.Text & arr(j) Next j End Sub
執行結果如下:
法二:土法煉鋼
Private Sub Command2_Click() Sub Command2_Click() ReDim Preserve arr(UBound(arr) + 1) Debug.Print UBound(arr) Dim i As Long, j As Long, m As Long, n As Long i = CLng(Text2.Text) n = CLng(Text3.Text) 2: If Val(i) > UBound(arr) - 1 Then MsgBox "您輸入的位置數值過大", , "信息提示" GoTo 2 Else For j = i To UBound(arr) '插入新數值 m = arr(j) arr(j) = n n = m Next j Text4.Text = "" For j = LBound(arr) To UBound(arr) If j <> 0 Then Text4.Text = Text4.Text & "," End If Text4.Text = Text4.Text & arr(j) Next j End If End Sub
Dim ary() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} Private Sub Form1_Load() Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.ListBox1.Items.Clear() Me.ListBox2.Items.Clear() For Each i As Integer In ary Me.ListBox1.Items.Add(i) Next End Sub Private Sub Button1_Click() Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ' 一整數陣列 Me.ListBox1.Items.Clear() Me.ListBox2.Items.Clear() Dim inarr As Integer = CInt(TextBox1.Text) Dim inst As Integer = CInt(TextBox2.Text) ary = InstArray(ary, inarr, inst) For Each i As Integer In ary ' Me.ListBox1.Items.Add(i) Me.ListBox2.Items.Add(i) Next End Sub Private Function InstArray() Function InstArray(ByRef Ary() As Integer, ByVal insarr As Integer, ByVal inst As Integer) As Integer() ' 使用 List 泛型類別 Dim lst As New List(Of Integer) For Each i As Integer In Ary lst.Add(i) Next lst.Insert(insarr, inst) Return lst.ToArray ' 將 List 的元素複製到新的陣列並回傳 End Function