我正在尝试创建一个小的userform调用日志。 用户获取详细信息并单击按钮,将使用文本框填充指定的Excel工作表。 我对VBA比较陌生,似乎无法使用指定的文本框填充当前行(应该为空)的列(例如,列A = tb1.text,列b = tb2.text) 我有“找空行”正常工作。 我已经删除了正确填充列的失败尝试,但需要保持与在Visual Studio中编写的格式相同的格式。
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btn_submit.Click
On Error Resume Next
Dim objExcel As New Microsoft.Office.Interop.Excel.Application
Dim objWorkbook As Microsoft.Office.Interop.Excel.Workbook
Dim objWorksheet As Microsoft.Office.Interop.Excel.Worksheet
objWorkbook = objExcel.Workbooks.Open("C:\_Private Data - NO BACKUP\Test OM Sheet.xlsx")
objWorksheet = CType(objWorkbook.Worksheets.Item("Sheet1"), Microsoft.Office.Interop.Excel.Worksheet)
Dim lastrow As Integer
lastrow = objWorksheet.Cells(objWorksheet.Rows.Count, 1).End(Excel.XlDirection.xlUp).Row + 1
Dim emptyrow As Integer = lastrow + 0,1
objWorksheet.Cells(emptyrow, 0) = tb_date_time.Text
objWorksheet.Cells(lastrow, 1) = tb_user_name.Text
objWorksheet.Cells(emptyrow, 1) = tb_date_time.Text
objWorksheet.Columns.AutoFit()
objWorkbook.Save()
objWorkbook.Application.DisplayAlerts = False
objWorkbook.SaveAs("C:\_Private Data - NO BACKUP\Test OM Sheet Backup.xlsx")
objWorkbook.Application.DisplayAlerts = True
objExcel.Quit()
Call reset_form()
End Sub
答案 0 :(得分:0)
我有"找到空行"工作正常
实际上,我认为这就是你的问题所在。这段代码:
Dim lastrow As Integer = objWorksheet.Cells.Rows.Count
Dim emptyrow As Integer = lastrow + 1
将返回1 +电子表格中最后一行,这将通过
中的错误objWorksheet.Cells(emptyrow, 1) = tb_date_time.Text
因为它会查找不存在的单元格行号。
试试这个。
Dim lastrow As Integer
lastrow = objWorksheet.Cells(objWorksheet.Rows.Count,1).End(xlup).Row + 1
Dim emptyrow As Integer = lastrow + 1
objWorksheet.Cells(emptyrow, 1) = tb_date_time.Text
我对VSTO并不熟悉,所以我的语法可能有点偏,但从概念上来说应该有用。
答案 1 :(得分:0)
嗯,它真的很乱,但这就是我最终的结果。我确定有更好的方法,但我已经转到了代码的下一部分。
public static int gcd(int a, int b) //Calculates the greatest common divider for two integers
{
if (b == 0) {
return a;
} else {
return gcd(b, a%b);
}
}