开发者

Add Contents of Cell to VBA Query

开发者 https://www.devze.com 2022-12-30 07:58 出处:网络
I would like to update my code to include the contents of a cell, S3. Right now the cell has the value of \'Test, Testing, Tested\' and the relevant part of the query looks like this:

I would like to update my code to include the contents of a cell, S3. Right now the cell has the value of 'Test, Testing, Tested' and the relevant part of the query looks like this:

SELECT * FROM dbo.Total WHERE ID = " & TextBox1.Text & " And Source IN (开发者_JS百科What do I put in here?)

Your help is much appreciated


How about something like this?

Dim someSQL As String
someSQL = "SELECT * FROM dbo.Total WHERE ID = " & TextBox1.Text & _
          " And Source IN (" & Sheet1.Cells(3, 19) & ")"

Substitute the appropriate sheet name for "Sheet1" as needed.


You will need to parse out, trim, escape and quote each of the 3 values in the cell to get:

SELECT * FROM dbo.Total WHERE ID = 'bob''s' And Source IN ('Test','Testing','Tested')

Using

Dim someSQL As String
someSQL = "SELECT * FROM dbo.Total WHERE ID = '" & escape(TextBox1.Text) & "' And Source IN (" & splitCell("s3") & ")"

Function splitCell(addr As String) As String
  Dim v() As String
  Dim i As Long
  v = Split(Range(addr).Value, ",")
  For i = 0 To UBound(v)
      v(i) = "'" & escape(trim$(v(i))) & "'"
  Next
  splitCell = Join(v, ",")
  If (Len(splitCell) = 0) Then splitCell = "''"
End Function

Function escape(sIn As String) As String
  //you should use a prepared statement instead
  escape = Replace$(sIn, "'", "''")
End Function
0

精彩评论

暂无评论...
验证码 换一张
取 消