excel - 从结果中排除选定的行
问题描述
我以前从未使用过 vb 脚本。我需要根据 excel 表中的一些示例数据生成插入语句。
我研究了一个 vb 宏,它为工作表中的所有列生成结果。
例如对于两行,它将生成如下结果:
insert into [Col1] ([col2], [col3], [col4], [col5c], [col6])
values
('ABC', 'PF', 'Loan_amount', 'GDTG/_Prod', 'IDW/logs'),
('DFGC', 'PF', 'Investment', 'GDTG/_Prod', 'ERW/logs')
现在,我有一个改变的要求。我在开头添加了另一列,其中包含一些值,如新、旧、删除等。
我希望仅在“新”标记的行上生成插入。例如在下面我只想要新的结果: 示例数据
另外,以下是我当前的脚本:
Sub GetInsertSQL()
Dim wsSrc As Worksheet: Set wsSrc = ActiveSheet
Dim LastRow As Long: LastRow = wsSrc.UsedRange.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Dim LastCol As Long: LastCol = wsSrc.UsedRange.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Dim i As Long, j As Long
Dim strQuery As String
Dim strOutput As String
strQuery = ""
For j = 1 To LastCol
strQuery = strQuery + "[" + CStr(wsSrc.Cells(1, j)) + "], "
Next j
strQuery = Left(strQuery, Len(strQuery) - 2)
strQuery = "insert into [" + wsSrc.Name + "] (" + strQuery + ")"
strOutput = strQuery + Chr(13) + Chr(10) + "values"
For i = 2 To LastRow
strQuery = ""
For j = 1 To LastCol
strQuery = strQuery + "'" + Replace(CStr(wsSrc.Cells(i, j).Text), "'", "''") + "', "
Next j
strQuery = "(" + Left(strQuery, Len(strQuery) - 2) + "), "
strOutput = strOutput + Chr(13) + Chr(10) + strQuery
Next i
strOutput = Left(strOutput, Len(strOutput) - 2)
OutputForm.txtOutput.Text = strOutput
OutputForm.Show vbModal
End Sub
解决方案
Sub GetInsertSQL()
Dim wsSrc As Worksheet: Set wsSrc = ActiveSheet
Dim LastRow As Long: LastRow = wsSrc.UsedRange.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Dim LastCol As Long: LastCol = wsSrc.UsedRange.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Dim i As Long, j As Long
Dim strQuery As String
Dim strOutput As String
strQuery = ""
For j = 1 To LastCol
strQuery = strQuery + "[" + CStr(wsSrc.Cells(1, j)) + "], "
Next j
strQuery = Left(strQuery, Len(strQuery) - 2)
strQuery = "insert into [" + wsSrc.Name + "] (" + strQuery + ")"
strOutput = strQuery + Chr(13) + Chr(10) + "values"
For i = 2 To LastRow
strQuery = ""
'Adding this if condition to check if value in 1st column is New
If (lcase(wsSrc.Cells(i, 1).Text) = "new") Then
For j = 1 To LastCol
strQuery = strQuery + "'" + Replace(CStr(wsSrc.Cells(i, j).Text), "'", "''") + "', "
Next j
strQuery = "(" + Left(strQuery, Len(strQuery) - 2) + "), "
strOutput = strOutput + Chr(13) + Chr(10) + strQuery
End If
Next i
strOutput = Left(strOutput, Len(strOutput) - 2)
OutputForm.txtOutput.Text = strOutput
OutputForm.Show vbModal
End Sub
推荐阅读
- ajax - 如何检查 shibboleth SSO 会话在 ajax 调用中是否过期?
- reactjs - React-router - 问题通过 url 访问路由
- tabs - 代码块编辑器不显示文件选项卡
- jupyter-notebook - 在 Jupyter Lab 文件浏览器上隐藏文件扩展名
- flutter - 使用代理将数据流式传输到 VideoPlayerController
- angular - 尝试运行 ng test 时出错:应该创建 FAILED
- r - 所有 .png 大小的总和
- grafana - Grafana 获得额外的 \\ 之前。我的变量名中的运算符
- c# - 唯一列表以及每个数字在原始列表中出现的次数
- rsync - 用于 rsync 文件的 SLURM 作业脚本