以前很难用vbnet排序excel工作表。 在工作簿中记录了一个宏,并尝试将代码转换过来,但是面临空引用异常。关于如何使这种工作有效的任何提示?
谢谢
代码
app = New Microsoft.Office.Interop.Excel.ApplicationClass
workbook= app.Workbooks.Open(workbook_name)
worksheet = CType(workbook.Worksheets(worksheet_name),Microsoft.Office.Interop.Excel.Worksheet)
range = CType(worksheet.Range("E4:E"+worksheet.UsedRange.Rows.Count.ToString),Microsoft.Office.Interop.Excel.Range)
worksheet.Sort.SortFields.Add(
Key:=range, _
SortOn:=Microsoft.Office.Interop.Excel.XlSortOn.xlSortOnValues, _
Order:=Microsoft.Office.Interop.Excel.XlSortOrder.xlDescending, _
DataOption:=Microsoft.Office.Interop.Excel.XlSortDataOption.xlSortNormal)
With worksheet.AutoFilter.Sort
.Header = Microsoft.Office.Interop.Excel.XlYesNoGuess.xlYes
.MatchCase = False
.Orientation = Microsoft.Office.Interop.Excel.XlSortOrientation.xlSortRows
.SortMethod = Microsoft.Office.Interop.Excel.XlSortMethod.xlPinYin
.Apply
End With
workbook.Save
workbook.Close
错误消息
_Test has thrown an exception
Source: Sort and Filter
Message: Exception has been thrown by the target of an invocation.
Exception Type: TargetInvocationException
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at UiPathCodeRunner_2980e99aec2a470db67f8b45c1524fdc.Run(Workbook workbook, Worksheet worksheet, Range range, GC GC, Application app, String worksheet_name, String workbook_name)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at UiPath.Core.Activities.Workflow.CompilerRunner.Run(Object[] args)
at UiPath.Core.Activities.InvokeCode.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.ActivityInstance.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)