我创建了一个宏来删除excel文件中空行的所有边框。这是迁移代码:
Sub RemoveRows()
'
' RemoveRows Macro
'
'
Range("A8").Select
Dim checkval
Dim RowAmount
RowAmount = 93
Do
checkval = ActiveCell.Value
If (checkval = "" Or checkval = Null) Then
ActiveCell.EntireRow.Delete
Else
ActiveCell.Offset(1, 0).Select
End If
RowAmount = RowAmount - 1
Loop While RowAmount > 0
End Sub
运行宏的方法:
public void RemoveRows_Macro(string fileName)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
xlWorkBook = xlApp.Workbooks.Open(fileName);
xlApp.DisplayAlerts = true;
//Run the macro
xlApp.Run("RemoveRows", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Save();
xlWorkBook.Close(false);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
}
我的问题是我可以从我的C#应用程序运行此宏而不会出现此错误,但当其他人使用我的C#应用程序时,他们会收到此错误:运行时错误“13”:类型不匹配
我做错了什么?
答案 0 :(得分:0)
要远离单元格格式,请始终使用Value2
。
始终标注变量类型,仅在需要时使用它们,checkval非常有用,您可以直接检查ActiveCell.Value2 = ""
或检查IsEmpty(ActiveCell)
。
如果您真的想要使用此变量,请将其标注为Variant
。
Excel单元格值不是NULL,它们至少为空或等于空字符串(“”),因此执行IsNull
或= NULL
检查在VBA中没有意义。跳过Null的检查,它应该可以正常工作。
答案 1 :(得分:0)
试试这个版本
它处理
""
(离开它们)的公式Sub RemoveRows()
Dim dat As Variant
Dim i As Long
Dim rng As Range, rngDel As Range
Dim str As String
Set rng = Range("A8:A100")
dat = rng.Formula
For i = 1 To UBound(dat, 1)
str = Replace$(dat(i, 1), Chr(160), "")
str = Replace$(str, vbCr, "")
str = Replace$(str, vbLf, "")
str = Replace$(str, vbTab, "")
If Len(Trim$(str)) = 0 Then
If rngDel Is Nothing Then
Set rngDel = rng.Cells(i, 1)
Else
Set rngDel = Application.Union(rngDel, rng.Cells(i, 1))
End If
End If
Next
If Not rngDel Is Nothing Then
rngDel.EntireRow.Delete
End If
End Sub
答案 2 :(得分:-2)
要尝试的几件事情:
string
或variant
或range
。IsNull(checkval)
函数代替checkval = Null
。
Empty
而非null
,使用isempty(a)
。len(trim(a)) = 0
作为支票。 代码:
Sub RemoveRows()
'
' RemoveRows Macro
'
'
Dim checkval as long, RowAmount as long
checkval = 8
RowAmount = 93
Do
'If trim(range("A" & checkval)) = "" Or _
' isempty(range("A" & checkval)) Then 'thanks chris
If Len(Trim(range("A" & checkval))) = 0 then
range("A" & checkval).EntireRow.Delete
Else
checkval = checkval + 1
End if
RowAmount = RowAmount - 1
Loop While RowAmount > 0
End Sub