Chuyên đề giải đáp những thắc mắc về code VBA

Liên hệ QC

maytinhvp01

Thành viên thường trực
Tham gia
27/7/13
Bài viết
390
Được thích
179
Mình muốn nhờ giải thich câu lệnh " If Ran.Cells(d, c) > max Then max = Ran.Cells(d, c) "
trong ví du:
Public Function LonNhat(Ran As Range)
Dim max As Double, v As Integer, d As Integer, c As Integer
max = Ran.Cells(1, 1)
For d = 1 To Ran.Rows.Count
For c = 1 To Ran.Columns.Count
If Ran.Cells(d, c) > max Then max = Ran.Cells(d, c)
Next c
Next d
v = Tim(max, Ran)
LonNhat = max
End Function
-------------------------------------------------------
[INFO1]Thông báo:
Vì topic này:
http://www.giaiphapexcel.com/forum/...ải-thích-các-code-đề-nghị-các-bạn-gửi-vào-đây
đã quá dài nên BQT đóng lại.
Nay tôi mở topic mới với cùng chủ đề: GIẢI THÍCH NHỮNG THẮC MẮC VỀ CODE
Các bạn nếu có nhu cầu giải thích code, vui lòng post tại đây nhé
NDU96081631

[/INFO1]
 
Chỉnh sửa lần cuối bởi điều hành viên:
E dùng InputBox:
Dim m as String
m = Application.InputBox(UNC("LÝ do in l¹i"), Type:=2) '(m là Text)

E muốn khi chọn Cancel thì sẽ nhảy đến nhãn Thoát chứ không phải chạy tiếp tục lệnh sau đó, thì dùng If như thế nào vậy ạ
 
Upvote 0
E dùng InputBox:
Dim m as String
m = Application.InputBox(UNC("LÝ do in l¹i"), Type:=2) '(m là Text)

E muốn khi chọn Cancel thì sẽ nhảy đến nhãn Thoát chứ không phải chạy tiếp tục lệnh sau đó, thì dùng If như thế nào vậy ạ
PHP:
m = Application.InputBox(UNC("LÝ do in l¹i"), Type:=2)           '(m là Text)
If m = "False" Then GoTo Thoat
Tuy nhiên, nếu bạn nhập vào InputBox chữ 'False' thì cũng nhảy đến nhãn Thoat. Muốn khắc phục thì phải sửa lại kiểu của biến m.
 
Upvote 0
PHP:
m = Application.InputBox(UNC("LÝ do in l¹i"), Type:=2)           '(m là Text)
If m = "False" Then GoTo Thoat
Tuy nhiên, nếu bạn nhập vào InputBox chữ 'False' thì cũng nhảy đến nhãn Thoat. Muốn khắc phục thì phải sửa lại kiểu của biến m.
E làm được rùi, thank bác ạ
 
Lần chỉnh sửa cuối:
Upvote 0
Nhờ các cao thủ thông não giúp e với ạ. trình độ e còn xanh quá nên ko hiểu cái này là như thế nào cả... cảm ơn các bác


Option Explicit
Type BarElement
Mark As String
Diameter As Byte
Quantity As Long
No As Long
Length As Double
End Type
Type BarDetail
Dia As Byte
MaxNum As Byte
TotalNum As Integer
CurrentNum As Integer
Mark As String
Length As Double
MinLength As Double
End Type
Public Type SumLength
Value As Double
Note As String
End Type
Public maxLength As Double
Public maxResult As Double
Public maxString As String
Public tmpBar As Integer
Public tmpNum As Byte
Public barIndex As Long
Public cutIndex As Long
Public lapLength As Double
Public devLength As Double
Public cutOption As Byte
Public constPI As Double
Public isDemo As Boolean

Public Sub CutBarMainControl()
Call GetInitialData
'isDemo = True
'If InStr(Application.Caption, "REGISTERED") <> 0 Then isDemo = True
'isDemo = True
'If isDemo = True Then
' If MsgBox("Not registered vesion. Run DEMO program?", vbInformation + vbYesNoCancel, "Before running") = vbYes Then
' 'Call mdlCreateRandom.CreateRandom
' Call SortInputData
' Else
' If MsgBox("Not registered vesion. Run DEMO program?", vbInformation + vbYesNoCancel, "Before running") = vbNo Then
' Load frmActivate
' frmActivate.Show
' End If
' End If
' Else
Call SortInputData
'End If
End Sub

Private Sub GetInitialData()
maxLength = Sheets("Input").Cells(2, 6)
devLength = Sheets("Input").Cells(3, 6)
lapLength = Sheets("Input").Cells(4, 6)
cutOption = Sheets("Input").Cells(5, 6)
cutIndex = 0
constPI = Application.WorksheetFunction.Pi()
'Clear old data in sheet Result
Sheets("Result").Activate
Cells(1, 5) = 0
Range("A4:K65536").Clear 'Number of row in a sheet is 65536
End Sub

Private Sub SortInputData()
ActiveWorkbook.Application.StatusBar = "Analyzing and sorting data..."
Dim arrDiameter(1 To 15) As Byte
Dim arrWeight(1 To 15) As Double
Dim arrBar(1 To 15, 1 To 500) As BarElement
Dim arrNum(1 To 15) As Long
Dim curBarDia As Byte
Dim curBarLength As Double
Dim curBarMark As String
Dim curBarQuantity As Long
Dim curBarNo As Long
Dim i&, j&, l&
Dim k As Byte
Dim tmpMu As Integer
'Initilize list of support Diameters
For i = 1 To 15
arrDiameter(i) = Sheets("Input").Cells(2, i + 8)
Next i
For i = 1 To 15
arrNum(i) = 0
arrWeight(i) = 0
Next i
'Set initial Cell Index
i = 9
Sheets("Input").Activate
Do While Trim(Cells(i, 4)) <> "" 'Cot duong kinh khac 0
Cells(i, 2) = i - 8
curBarNo = i - 8
curBarMark = Trim(Cells(i, 3))
curBarDia = Trim(Cells(i, 4))
curBarQuantity = Trim(Cells(i, 5))
curBarLength = Trim(Cells(i, 6))
For j = 1 To 15
If arrDiameter(j) = curBarDia Then
arrNum(j) = arrNum(j) + 1
arrBar(j, arrNum(j)).No = curBarNo
arrBar(j, arrNum(j)).Mark = curBarMark
arrBar(j, arrNum(j)).Diameter = curBarDia
arrBar(j, arrNum(j)).Quantity = curBarQuantity
arrBar(j, arrNum(j)).Length = curBarLength
arrWeight(j) = arrWeight(j) + (((curBarDia ^ 2 * constPI / 4) * curBarLength) * 7850 * curBarQuantity) / 1000000
Exit For
End If
Next j
i = i + 1
Loop
Range("B9:G" & i - 1).Select
Call FormatInputTable
Range("B9:C" & i - 1).Select
Selection.HorizontalAlignment = xlCenter

'Dien DK va khoi luong vao Remain
For i = 1 To 15
Sheets("Remain").Cells(i + 3, 7) = arrDiameter(i)
Sheets("Remain").Cells(i + 3, 8) = arrWeight(i)
Next i
Sheets("Result").Activate
For j = 1 To 15
If arrNum(j) > 0 Then
ActiveWorkbook.Application.StatusBar = "Filtering data to Diameter: " & arrDiameter(j)
'Get current row index
barIndex = Cells(1, 5)
'Transfer data to ActiveSheet
l = 0
For i = 1 To arrNum(j)
l = l + 1
If arrBar(j, i).Length > maxLength Then
tmpMu = Int(arrBar(j, i).Length / (maxLength - lapLength * arrDiameter(j) / 1000))
Cells(barIndex + l + 3, 1) = arrBar(j, i).No
Cells(barIndex + l + 3, 2) = arrBar(j, i).Diameter
Cells(barIndex + l + 3, 3) = arrBar(j, i).Mark
Cells(barIndex + l + 3, 4) = arrBar(j, i).Quantity * tmpMu
Cells(barIndex + l + 3, 5) = maxLength
l = l + 1
arrBar(j, i).Length = arrBar(j, i).Length - tmpMu * (maxLength - lapLength * arrDiameter(j) / 1000)
End If
Cells(barIndex + l + 3, 1) = arrBar(j, i).No
Cells(barIndex + l + 3, 2) = arrBar(j, i).Diameter
Cells(barIndex + l + 3, 3) = arrBar(j, i).Mark
Cells(barIndex + l + 3, 4) = arrBar(j, i).Quantity
Cells(barIndex + l + 3, 5) = arrBar(j, i).Length
Next i
Cells(1, 5) = Cells(1, 5) + l
'Sort data
Range("A" & barIndex + 3 & ":E" & barIndex + l + 3).Select
Selection.Sort key1:=Range("E" & barIndex + 3), Order1:=xlDescending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
ActiveWorkbook.Application.StatusBar = "Opimizing cutting bar for Diameter: " & arrDiameter(j)
'Format data from column A to D
Range("A" & barIndex + 4 & ":D" & barIndex + l + 3).Select
Selection.NumberFormat = "0"
Selection.HorizontalAlignment = xlCenter
'Format data from column A to E
Range("E" & barIndex + 4 & ":E" & barIndex + l + 3).Select
Selection.NumberFormat = "0.000"
'Format cell borders
Range("A" & barIndex + 4 & ":E" & barIndex + l + 3).Select
Call FormatInputTable
Call CutbarAnalyze(arrDiameter(j))
Range("A" & barIndex + 3 & ":E" & barIndex + l + 3).Select
Selection.Sort key1:=Range("A" & barIndex + 3), Order1:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom
End If
Next j
ActiveWorkbook.Application.StatusBar = "Controlling remain steel for the next usage"
Cells(1, 9) = "Optimization finished!"
Call ControlRemainSteel
ActiveWorkbook.Application.StatusBar = "Ready"
End Sub

Private Sub ClearCurrentSheet(intCount As Long)
Dim i&, j&
Cells(1, 6) = ""
i = 4
Do While Trim(Cells(i, 5) <> "")
i = i + 1
Loop
j = i
If intCount >= j Then j = intCount
Rows("4:" & j).Select
Selection.Delete Shift:=xlUp

End Sub

Private Sub CutbarAnalyze(curBarDiameter)
Dim i&, j&, k&, l&, m&, iPos&
Dim sCnt&, iCnt&
Dim MaxBar As Long
Dim iniLength As Double
Dim useLength As Double
Dim resLength As Double
Dim maxNumUse As Long
Dim strKey As String
Dim strAnl As String
Dim curMaxNum As Byte
Dim curBar() As BarDetail
Dim curNum() As Integer
Dim curFac() As Integer
Dim curSumLength(1 To 500) As SumLength
Dim curSumMin(1 To 500) As SumLength
Dim curCOM(1 To 500) As SumLength
Dim strNum(1 To 500) As String
Dim strDisplay As String
'Get MaxBar form current sheet
MaxBar = Cells(1, 5)
'ReDefined array
If MaxBar > 0 Then
ReDim curBar(1 To MaxBar) As BarDetail
ReDim curNum(1 To MaxBar) As Integer
ReDim curFac(1 To MaxBar) As Integer
iniLength = 0
useLength = 0
For i = barIndex + 1 To MaxBar
curBar(i).Mark = Cells(i + 3, 3)
curBar(i).TotalNum = Cells(i + 3, 4)
curBar(i).CurrentNum = Cells(i + 3, 4)
curBar(i).Length = Cells(i + 3, 5)
iniLength = iniLength + curBar(i).Length * curBar(i).TotalNum
curBar(i).MinLength = curBar(i).Length * (1 - devLength)
curBar(i).MaxNum = Fix(maxLength / curBar(i).MinLength)
Next i
'Cells index to put result
i = 1
iPos = 4
Do While i <= MaxBar
Do While curBar(i).CurrentNum > 0
sCnt = 0
For j = 1 To minValue(curBar(i).MaxNum, curBar(i).CurrentNum)
sCnt = sCnt + 1
curSumLength(sCnt).Value = j * curBar(i).Length
curSumMin(sCnt).Value = j * curBar(i).MinLength
curSumLength(sCnt).Note = "Bar" & i & "Num" & j
Next j
k = i + 1
Do While k <= MaxBar
If curBar(k).CurrentNum > 0 Then
m = 0
For iCnt = 1 To sCnt
For l = 1 To minValue(curBar(k).MaxNum, curBar(k).CurrentNum)
'curSumLength(iCnt).Value + l * curBar(k).Length <= maxlength Or
If curSumMin(iCnt).Value + l * curBar(k).MinLength <= maxLength Then
m = m + 1
curSumLength(sCnt + m).Value = curSumLength(iCnt).Value + l * curBar(k).Length
curSumMin(sCnt + m).Value = curSumMin(iCnt).Value + l * curBar(k).MinLength
curSumLength(sCnt + m).Note = curSumLength(iCnt).Note & "Bar" & k & "Num" & l
End If
Next l
Next iCnt
sCnt = sCnt + m
End If
k = k + 1
Loop
Call get_MaxResult(curSumLength, sCnt)
'Get conresponded num of bar in this case -> curNum(1 To MaxBar)
For j = 1 To MaxBar
curNum(j) = 0
Next j
j = 2
Do While j <= Len(maxString)
strKey = Mid(maxString, j, 3)
If strKey = "Bar" Then
strAnl = Left(maxString, j - 1)
Call get_NumBar(strAnl)
curNum(tmpBar) = tmpNum
maxString = Right(maxString, Len(maxString) - j + 1)
j = 2
Else
j = j + 1
End If
Loop
Call get_NumBar(maxString)
curNum(tmpBar) = tmpNum
'Get maximun combination in this case -> maxNumUse(curNum, curBar.CurrentNum)
For j = 1 To MaxBar
If curNum(j) <> 0 Then
curFac(j) = curBar(j).CurrentNum \ curNum(j)
Else
curFac(j) = 0
End If
Next j
maxNumUse = maxArray(curFac)
For j = 1 To MaxBar
If maxNumUse >= curFac(j) Then
If curFac(j) > 0 Then
maxNumUse = curFac(j)
End If
End If
Next j
'Write analysis result to sheet
'Writing diameter
'barIndex = get_CurrentIndex()
Cells(cutIndex + iPos, 7) = curBarDiameter
'Writing cut No.
Cells(cutIndex + iPos, 8) = iPos - 3
strDisplay = ""
resLength = 0
For j = 1 To MaxBar
If curNum(j) > 0 Then
strDisplay = strDisplay & curNum(j) & "*[" & curBar(j).Mark & "]+"
resLength = resLength + curNum(j) * curBar(j).Length
End If
Next j
strDisplay = Left(strDisplay, Len(strDisplay) - 1)
Cells(cutIndex + iPos, 9) = strDisplay
Cells(cutIndex + iPos, 10) = maxNumUse
Cells(cutIndex + iPos, 11) = resLength
useLength = useLength + maxLength * maxNumUse
For j = 1 To MaxBar
curBar(j).CurrentNum = curBar(j).CurrentNum - maxNumUse * curNum(j)
Next j
iPos = iPos + 1
Loop
i = i + 1
Loop
'Format cell borders
Range("G" & cutIndex + 4 & ":K" & cutIndex + iPos - 1).Select
Call FormatInputTable
'Number format
Range("K" & cutIndex + 4 & ":K" & cutIndex + iPos - 1).Select
Selection.NumberFormat = "0.000"
cutIndex = cutIndex + iPos - 4
End If
End Sub
Private Sub ControlRemainSteel()
Dim arrDiameter(1 To 15) As Byte
Dim arrMinLength(1 To 15) As Double
Dim arrRealWeigth(1 To 15) As Double
Dim tmpWeight As Double
Dim i%, j%, k%
Dim curMinLength As Double
For i = 1 To 15
arrMinLength(i) = Sheets("Input").Cells(3, i + 8)
arrDiameter(i) = Sheets("Input").Cells(2, i + 8)
Next i

'Clear old data in this sheet
Sheets("Remain").Activate
Range("A4:E65536").Clear
'For i = 1 To 15
'Filter remain steel for next usage
j = 4
k = 0
Do While Trim(Sheets("Result").Cells(j, 9)) <> ""
For i = 1 To 15
If Sheets("Result").Cells(j, 7) = arrDiameter(i) Then
curMinLength = arrMinLength(i)
Exit For
End If
Next i
If maxLength - Sheets("Result").Cells(j, 11) >= curMinLength Then
k = k + 1
Cells(k + 3, 1) = k
Cells(k + 3, 2) = Sheets("Result").Cells(j, 7)
Cells(k + 3, 3) = Sheets("Result").Cells(j, 8)
Cells(k + 3, 4) = Sheets("Result").Cells(j, 10)
Cells(k + 3, 5) = maxLength - Sheets("Result").Cells(j, 11)
End If
j = j + 1
Loop
'Format number
Range("E4:E" & k + 3).Select
Selection.NumberFormat = "0.000"
'Format range
Range("A4:E" & k + 3).Select
Call FormatInputTable
'Get reality weight
j = 4
Do While Trim(Sheets("Result").Cells(j, 9)) <> ""
For i = 1 To 15
If Sheets("Result").Cells(j, 7) = arrDiameter(i) Then
tmpWeight = arrDiameter(i) ^ 2 * constPI / 4 / 10 ^ 6
tmpWeight = tmpWeight * Sheets("Result").Cells(j, 10) * maxLength * 7850
arrRealWeigth(i) = arrRealWeigth(i) + tmpWeight
Exit For
End If
Next i
j = j + 1
Loop
'Writing data
For i = 1 To 15
Cells(i + 3, 9) = arrRealWeigth(i)
Next i
'Next i

End Sub

Public Function minValue(valA, valB) As Double
minValue = valA
If minValue >= valB Then minValue = valB
End Function

Private Sub get_MaxResult(arrBar() As SumLength, arrCnt As Long)
maxResult = arrBar(1).Value
maxString = arrBar(1).Note
Dim i&
For i = 1 To arrCnt
If arrBar(i).Value >= maxResult Then
maxResult = arrBar(i).Value
maxString = arrBar(i).Note
End If
Next i
End Sub

Private Sub get_NumBar(strGet)
tmpNum = 0
tmpBar = 0
Dim i1 As Integer
For i1 = 1 To Len(strGet)
If Mid(strGet, i1, 3) = "Num" Then
tmpBar = Right(Left(strGet, i1 - 1), Len(Left(strGet, i1 - 1)) - 3)
tmpNum = Right(Right(strGet, Len(strGet) - i1 + 1), Len(Right(strGet, Len(strGet) - i1 + 1)) - 3)
Exit For
End If
Next i1

End Sub
Private Function maxArray(arrFac() As Integer) As Integer
maxArray = 0
Dim iArr As Integer
For iArr = LBound(arrFac) To UBound(arrFac)
If maxArray <= arrFac(iArr) Then maxArray = arrFac(iArr)
Next iArr

End Function

Private Function Num2Char(intNum As Integer) As String
Num2Char = ""
Do While intNum > 26
Num2Char = Chr(64 + intNum Mod 26) & Num2Char
intNum = intNum \ 26
Loop
Num2Char = Chr(64 + intNum) & Num2Char
End Function

Private Function get_CurrentIndex()
Dim cIndex As Long
cIndex = 4
Do While Trim(Cells(cIndex, 7)) <> ""
cIndex = cIndex + 1
Loop
get_CurrentIndex = cIndex
End Function


Private Sub FormatInputTable()
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlHairline
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlHairline
.ColorIndex = xlAutomatic
End With
End Sub



 

File đính kèm

  • abc.xls
    199.5 KB · Đọc: 7
  • code.txt
    16.1 KB · Đọc: 2
Lần chỉnh sửa cuối:
Upvote 0
Xin nhờ cao thủ giúp em vấn đề này với.
Trong WORD em có đoạn văn bản như sau:
< bR>
Chào các bạn
< bR>
Hôm nay trời đẹp
< bR>
Kết thúc

Em muốn viết đoạn code để tự động tìm và thay thế chữ "<bR>" theo quy tắc
Câu 1
Chào các bạn
Câu 2
Hôm nay trời đẹp
Câu 3
Kết thúc

Tức là vừa tìm chữ <bR> vừa đếm xem nó là chữ xuất hiện lần thứ i và thay bằng chữ "Câu i".
Em cần gấp lắm mong được sự cứu giúp của anh em trong diễn đàn lắm ạ.
Em xin chân thành cảm ơn.
 
Lần chỉnh sửa cuối:
Upvote 0
Mình tìm đc đoan code này ở trên mạng:
Sub run_sql_sub(sql)
On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")


With cn
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
ThisWorkbook.FullName _
& ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"
.Open
End With
rs.Open sql, cn


Application.ScreenUpdating = False
ActiveSheet.Range("A2:XFD1048576").ClearContents


For intColIndex = 0 To rs.Fields.Count - 1
Range("A2").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next


Range("A3").CopyFromRecordset rs
Application.ScreenUpdating = True
rs.Close: cn.Close: Set rs = Nothing: Set cn = Nothing
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range


Set KeyCells = ActiveSheet.Range("A1")

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then


If InStr(KeyCells.Value2, "mi_sql") > 0 Then
sql = Right(KeyCells.Value2, Len(KeyCells.Value2) - Len("mi_sql "))
run_sql_sub sql
End If

End If

End Sub

Nhưng mỗi lần cần chạy câu lệnh SQL trong ô A1 lại phải đưa con trỏ lên ô A1 và ấn Enter. Bây giời mình muốn sửa lại để môi lần thay đổi là câu lệnh SQL tự động thực hiện. Cảm ơn
 

File đính kèm

  • Excel 67 SQL trong EXCEL.rar
    460.3 KB · Đọc: 48
Upvote 0
Nhưng mỗi lần cần chạy câu lệnh SQL trong ô A1 lại phải đưa con trỏ lên ô A1 và ấn Enter. Bây giời mình muốn sửa lại để môi lần thay đổi là câu lệnh SQL tự động thực hiện. Cảm ơn
Bạn nói rõ hơn, mỗi lần thay đổi là thay đổi thế nào không vậy, tức là thay đổi ở các ô khác hay sao?
- Nếu bạn muốn thay đổi 1 vùng từ A1 đến B10 đi chẳng hạn thì code thực hiện: bạn chỉ cần thay dòng: Set KeyCells = ActiveSheet.Range("A1") ====> Set KeyCells = ActiveSheet.Range("A1:B10"). Nói chung bạn chỉ cần thay đổi trong đó vùng bạn tác động
 
Upvote 0
Mình tìm đc đoan code này ở trên mạng:
Sub run_sql_sub(sql)
On Error Resume Next
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")


With cn
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
ThisWorkbook.FullName _
& ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"
.Open
End With
rs.Open sql, cn


Application.ScreenUpdating = False
ActiveSheet.Range("A2:XFD1048576").ClearContents


For intColIndex = 0 To rs.Fields.Count - 1
Range("A2").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next


Range("A3").CopyFromRecordset rs
Application.ScreenUpdating = True
rs.Close: cn.Close: Set rs = Nothing: Set cn = Nothing
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range


Set KeyCells = ActiveSheet.Range("A1")

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then


If InStr(KeyCells.Value2, "mi_sql") > 0 Then
sql = Right(KeyCells.Value2, Len(KeyCells.Value2) - Len("mi_sql "))
run_sql_sub sql
End If

End If

End Sub

Nhưng mỗi lần cần chạy câu lệnh SQL trong ô A1 lại phải đưa con trỏ lên ô A1 và ấn Enter. Bây giời mình muốn sửa lại để môi lần thay đổi là câu lệnh SQL tự động thực hiện. Cảm ơn

gõ HCM,DANANG,HANOI vào ô A1
Mã:
Private Sub Worksheet_Change(ByVal Target As Range)
    
    If Target.Address = "$A$1" Then
            sql = "select * from [vpp] where region=" & "'" & [A1] & "'"
            run_sql_sub sql
    End If
    
End Sub
 
Upvote 0
Các bác cho em hỏi 1 chút ạ. Trong Macro setting của em, sao cái dấu tích trust access to the vba project object model - Nó bị mờ đi ạ, k tích được, cũng k bỏ tích được. Như vậy liệu có ảnh hưởng đến các code VBA của mình ko ạ
 
Upvote 0
Các bác cho em hỏi 1 chút ạ. Trong Macro setting của em, sao cái dấu tích trust access to the vba project object model - Nó bị mờ đi ạ, k tích được, cũng k bỏ tích được. Như vậy liệu có ảnh hưởng đến các code VBA của mình ko ạ

Cũng chẳng sao cả, nhưng nếu bạn muốn nó "bình thường" trở lại thì làm như sau:
- Đóng toàn bộ Excel
- Bấm tổ hợp phím Windows + R (lá cờ windows và phím R)
- Gõ REGEDIT vào khung Open rồi Enter
- Duyệt tới đường dẫn:
Mã:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\[COLOR=#ff0000]16.0[/COLOR]\Excel\Security
(Con số 16.0 màu đỏ ở trên là tùy theo phiên bản Office nha)
- Nhìn khung bên phải, nếu thấy mục có tên AccessVBOM thì xóa phéng nó đi
- Khởi động Excel và kiểm tra lại mục "Trust access.... "
 
Upvote 0
Cũng chẳng sao cả, nhưng nếu bạn muốn nó "bình thường" trở lại thì làm như sau:
- Đóng toàn bộ Excel
- Bấm tổ hợp phím Windows + R (lá cờ windows và phím R)
- Gõ REGEDIT vào khung Open rồi Enter
- Duyệt tới đường dẫn:
Mã:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\[COLOR=#ff0000]16.0[/COLOR]\Excel\Security
(Con số 16.0 màu đỏ ở trên là tùy theo phiên bản Office nha)
- Nhìn khung bên phải, nếu thấy mục có tên AccessVBOM thì xóa phéng nó đi
- Khởi động Excel và kiểm tra lại mục "Trust access.... "
Theo đường dẫn của bác NDU thì nó hem ra ạ, mà e find trong regitry thì cái AccessVBOM nó nằm ở đường dẫn này ạ: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Office\15.0\Excel\Security
Thêm cái mục lớn là Policies nữa ạ. e Đã xóa rùi, mà trong Excel - Marco seting - Cái trust access to the vba project object model nó vẫn bị mờ ạ.
Nhưng bác NDU đã nói k vấn đề gì thì ok ,kệ bố nó :D. Thank bác nhìu. Chúc bác ngày cuối tuần vui vẻ ạ --=0
 
Upvote 0
Thuộc tính End trong VBA: [C65536].End(3)(1, 2). Các bác cho em hỏi, cái phần e bôi đậm nghĩa là sao vậy ạ !
 
Upvote 0
Thuộc tính End trong VBA: [C65536].End(3)(1, 2). Các bác cho em hỏi, cái phần e bôi đậm nghĩa là sao vậy ạ !

Truy xuất na ná như hàm INDEX ấy
Giả sử [C65536].End(3) ra được kết quả là cell C15 đi nha. Vậy cái tô đậm kia sẽ index 1 dòng 2 cột, ra kết quả là cell D15
Tổng quát:
Tham chiếu(m, n) sẽ cho kết quả cell có dòng thứ m, cột thứ n tính từ cell tham chiếu
Lưu ý:
- Tại vị trí cell tham chiếu được tính là dòng 1, cột 1
- m và n có thể có giá trị âm
 
Lần chỉnh sửa cuối:
Upvote 0
Truy xuất na ná như hàm INDEX ấy
Giả sử [C65536].End(3) ra được kết quả là cell C15 đi nha. Vậy cái tô đậm kia sẽ index 1 dòng 2 cột, ra kết quả là cell D15
Tổng quát:
Tham chiếu(m, n) sẽ cho kết quả cell có dòng thứ m, cột thứ n tính từ cell tham chiếu
Lưu ý:
- Tại vị trí cell tham chiếu được tính là dòng 1, cột 1
- m và n có thể có giá trị âm


Vậy mình có thể dùng offset ko ạ. [C65536].end(3).offset(m,n). 2 cách này có khác nhau ko ạ
 
Upvote 0
Trong Sub này

Sub TinhTien()
On Error Resume Next
For Each cls In Range([c3], [c65536].End(3))
If cls > 0 Then
cls(1, 2) = Sheets("Don Gia").Cells.Find(cls(1, 0), , , 2)(1, 2)
cls(1, 3) = cls * cls(1, 2)
End If
Next
End Sub

Cho e hỏi với ạ: Tại vị trí em bôi đậm, e chưa hiểu điều kiện cần tìm này là gì ạ !
 
Upvote 0
Trong Sub này

Sub TinhTien()
On Error Resume Next
For Each cls In Range([c3], [c65536].End(3))
If cls > 0 Then
cls(1, 2) = Sheets("Don Gia").Cells.Find(cls(1, 0), , , 2)(1, 2)
cls(1, 3) = cls * cls(1, 2)
End If
Next
End Sub

Cho e hỏi với ạ: Tại vị trí em bôi đậm, e chưa hiểu điều kiện cần tìm này là gì ạ !
Giả sử cls là ô C7 thì cls(1,0) là ô B7.
 
Upvote 0
Truy xuất na ná như hàm INDEX ấy
Giả sử [C65536].End(3) ra được kết quả là cell C15 đi nha. Vậy cái tô đậm kia sẽ index 1 dòng 2 cột, ra kết quả là cell D15
Tổng quát:
Tham chiếu(m, n) sẽ cho kết quả cell có dòng thứ m, cột thứ n tính từ cell tham chiếu
Lưu ý:
- Tại vị trí cell tham chiếu được tính là dòng 1, cột 1
- m và n có thể có giá trị âm
Xin thầy chia sẽ thêm là: tham chiếu kiểu này và offset cơ bản có cùng bản chất, vậy sử dụng cái nào sẽ tối ưu hơn ạ, và thầy thường sử dụng phương pháp nào, em cám ơn
 
Upvote 0
Web KT
Back
Top Bottom