Noob在这里。我在2011年参加了编码课程,学习了一些VB5。需要有关此代码的帮助。它不会写入"C:\Users\Dibs\Documents\Sample32.xlsx"
。它也不抛出任何错误。因此无需调试。
此代码用于打开一个新的Excel文件,但是我需要写一个现有的文件。我在这里做错了什么?
我需要与此人相同的帮助。Outlook-How to open existing Excel file?
Option Explicit On
Imports Microsoft.Office.Interop
Dim objxlapp As Excel.Application
Dim objxlwrkbk As Excel._Workbook
Dim xlwrkbks As Excel.Workbooks
Dim xlwrkshts As Excel.Sheets
Dim xlwrksht As Excel._Worksheet
Dim range As Excel.range
' Create a new instance of Excel and start a new workbook.
'part of old code
'objxlapp = New Excel.Application()
'objxlwrkbk = xlwrkbks.Add
'this is where my troubles begin
'i cant figure out which variable or object needs the location info of the excel file
'that i want to write the array too
xlwrkbks = objxlapp.Workbooks.Open("C:\Users\Dibs\Documents\Sample32.xlsx")
objxlwrkbk = xlwrkbks
xlwrkshts = objxlwrkbk.Worksheets
xlwrksht = xlwrkshts(1)
'Get the range where the starting cell has the address
'm_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
range = xlwrksht.range("A1", Reflection.Missing.Value)
range = range.Resize(22, 22)
If (Me.FillWithStrings.Checked = False) Then
'Create an array.
Dim saRet(22, 22) As Double
'Fill the array.
Dim iRow As Long
Dim iCol As Long
For iRow = 0 To 22
For iCol = 0 To 22
'Put a counter in the cell.
saRet(iRow, iCol) = iRow * iCol
Next iCol
Next iRow
'Set the range value to the array.
range.Value = saRet
Else
'Create an array.
Dim saRet(22, 22) As String
'Fill the array.
Dim iRow As Long
Dim iCol As Long
For iRow = 0 To 22
For iCol = 0 To 22
'Put the row and column address in the cell.
saRet(iRow, iCol) = iRow.ToString() + "|" + iCol.ToString()
Next iCol
Next iRow
'Set the range value to the array.
range.Value = saRet
End If
'Return control of Excel to the user.
objxlapp.Visible = True
objxlapp.UserControl = True
'Clean up a little.
range = Nothing
xlwrksht = Nothing
xlwrkshts = Nothing
xlwrkbks = Nothing
objxlwrkbk.Save()
objxlwrkbk.Close()
objxlapp.Quit()
答案 0 :(得分:0)
Range
对象期望数组的下限为1-不为零。另外,接收范围的尺寸必须与数组的尺寸匹配。为此,您需要手动创建此类数组。
示例:
Option Infer On
Private Sub TestExcel()
Dim xlApp As New Excel.Application With {.Visible = True}
Dim xlBook = xlApp.Workbooks.Add()
Dim xlSheet = DirectCast(xlBook.Sheets(1), Excel.Worksheet)
'// Create array with custom lower bounds
'// 5 = number of rows
'// 2 = number of columns
'// {1, 1} = lower bounds for rows and columns, respectively
Dim arr = Array.CreateInstance(GetType(Integer), {5, 2}, {1, 1})
arr.SetValue(1, 1, 1) '//Assign '1' to first row, first column
arr.SetValue(50, 1, 2) '//Assign '50' to first row, second column
arr.SetValue(2, 2, 1) '//Assign '2' to second row, first column
arr.SetValue(100, 2, 2) '//Assign '1' to second row, second column
'// Transfer array to sheet
xlSheet.Range("A1:B5").Value = arr
' Other stuff - saving, closing etc.
End Sub